New Jul 25, 2024

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

More Front-end Bloggers All from Manuel Matuzović - Blog View Day 108: the of S syntax in :nth-child() on matuzo.at

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().

My blog doesn't support comments yet, but you can reply via blog@matuzo.at.

Scroll to top