Day 108: the of S syntax in :nth-child()

posted on

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.


You can use the of S syntax in the :nth-child() pseudo-class to filter elements before the arguments in :nth-child() apply.

The S in of S stands for a forgiving selector list.

/* :nth-child(An+B [of S]?) */ 
tr:nth-child(even of .visible, .active) { }

Let's say you have six list items and want to highlight every second item, but two of them are hidden.

HTML

<ol>
  <li>Element 1</li>
  <li hidden>Element 2</li>
  <li>Element 3</li>
  <li>Element 4</li>
  <li hidden>Element 5</li>
  <li>Element 6</li>
</ol>

CSS

li:nth-child(even) {
  background-color: aqua;
}
  1. Element 1
  2. Element 3
  3. Element 4
  4. Element 6

That works, but it probably differs from what you expected because the selector also applies to the hidden elements. The of S syntax allows you to prefilter the list of selectors and exclude all hidden items.

CSS

li:nth-child(even of :not([hidden])) {
  background-color: aqua;
}
  1. Element 1
  2. Element 3
  3. Element 4
  4. Element 6

You can also use it with :nth-last-child().

See on CodePen

Further reading

Overview: 100 Days Of More Or Less Modern CSS