Stylus nth-of-m-child(n,m) Selector

.

As explained/linked in (ab)using CSS3’s :nth-child() selector to invent new ones and Quantity Queries for CSS it’s possible to create new types of CSS selectors by cleverly combining a few the available CSS pseudo selectors. One of those new selectors is the :nth-of-m-child selector:

/**
 * :nth-of-m-child selector
 * This selector will select the 3rd child in a row of 5 elements
 */
span:nth-child(3):nth-last-child(3) {
  background: red;
}

The math behind it is easy: the value for the nth-child part in the selector is n, the value for the nth-last-child part in the selector is m - n + 1.

~

For a Stylus-based project I’m working on I was wondering if I could actually create this type of selector by name and also use it by its name. That way it’d save me some extra type and math work. Above that the resulting code would be more easy to understand.

After some fiddling I ended up with a function that returns the selector with its correct values injected:

// Selects child at position n in a group of m children
nth-of-m-child($n, $m)
  "nth-child(" + $n + "):nth-last-child(" + ($m - $n + 1) + ")"

The resulting selector – nth-of-m-child – can be used like any other pseudo selector right inside Stylus, but does need to be wrapped in between curly brackets in order for the returned string to be evaluated:

li
  // 1st out of 2
  &:{nth-of-m-child(1, 2)}
    background blue

  // 2nd out of 4
  &:{nth-of-m-child(2, 4)}
    background lime

  // 3rd out of 5
  &:{nth-of-m-child(3, 5)}
    background red

A demo pen with this code is embedded at the top of this post.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.