brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: :nth-child(even of .visible) in CSS keeps zebra stripes right after filtering

Css
~/tips/tip-css-nth-child-of-selector

tr:nth-child(even of :not([hidden])) {

Striped rows stay alternating even when a filter hides some rows.

Zebra striping a table breaks as soon as a filter hides rows, because :nth-child(even) still counts the hidden ones. The of syntax counts only the elements you care about.

tr:nth-child(even of :not([hidden])) {
  background: #f3f6fa;
}

Plain :nth-child(even) counts every sibling. With of S the browser first filters the siblings to those matching selector S and then counts within that list. So the second, fourth and sixth visible rows get the background, whatever is hidden between them.

It works for more than tables. li:nth-child(-n + 3 of .featured) picks the first three featured items in a list, and .card:nth-child(1 of .new) finds the first card with the class, which :first-child cannot do.

This is different from :nth-of-type(), which only filters by element name. The of form takes any selector list.

Safari had this for years, and Chrome 111 and Firefox 113 caught up in 2023, so it is safe for current browsers. I would still check how it looks in an old browser if your visitors use one, since there the whole rule is dropped and the rows lose their stripes.

Further reading: MDN: :nth-child()

More Css tips CSS Overview in Chrome DevTools audits the colors and fonts of a page .notice:empty { .toast { article { counter-reset: h2; } .toolbar { All Css tips (66) All topics

Link