Explain Codes LogoExplain Codes Logo

Styling every 3rd item of a list using CSS

css
responsive-design
best-practices
performance
Anton ShumikhinbyAnton Shumikhin·Nov 19, 2024
TLDR

Utilize the CSS pseudo-class :nth-child with the 3n pattern for directly targeting every 3rd item in a list:

li:nth-child(3n) { color: blue; /* Turns every third list item blue */ }

This neat CSS snippet targets <li> elements in a sequence — the 3rd, 6th, 9th, and so on, applying the defined style.

This method is super efficient for any sequential designs in a 960px wide div, leveraging the 3x3 grid layout, keeping your HTML clean, readable, and manageable.

Peeling back the layers of :nth-child(3n)

The :nth-child(3n) selector is efficiency personified in CSS. It targets the third element in a sequence — so in other words, every 3rd, 6th, 9th, and so forth.

Gridlock? Not on my watch

Hypothetically, we have a series of list items housed within a 960px div. The objective: to achieve a neatly aligned, OCD-friendly 3x3 grid. Here’s the magic spell:

li:nth-child(3n) { margin-right: 0; /* Eliminates the gap on the right for every 3rd item, neat and tidy! */ }

This not only maintains your grid structure, but does so without any extra classes or complex selectors. CSS magic!

Playing nice in the browser sandbox

The nth-child(3n) is a mature and widely supported operation in modern browsers — Chrome, Firefox, IE9+, and more. For the old-timers, with older versions of IE, you’ll need a workaround — think Javascript or conditional class assignments.

Expanding the horizon with :nth-child beyond margins

Styling across dimensions

Think beyond color. Consider background, and even transformations. The :nth-child(3n) is a dynamic selector arming you with differentiation superpower — think image galleries, product lists, etc.

Don't sacrifice accessibility for aesthetics

Any changes should always consider accessibility. While :nth-child(3n) is a great tool to add contrast and emphasis, always ensure that contrast ratios don't interfere with readability.

Cascade responsibly

When using the :nth-child, remember that it cascades. Use the direct child combinator (>) to ensure only direct descendants are targeted, like this:

ul > li:nth-child(3n) { font-weight: bold; /* Bold text for every 3rd item... Power level: over 9000! */ }

Troubleshooting 101 with :nth-child

The Cascade Clash

Keep an eye on specificity wars with other selectors. The :nth-child(3n) selection could be superseded by a more specific selector, or one that's sneakily hidden later in the CSS. Be strategic with the cascade and specificity.

Optimizing selector performance

While :nth-child(3n) is lean, overuse or misuse can slow performance. Keep your selectors as fit as possible and monitor your site to safeguard its performance.