Bits Kingdom logo with a hexagon lattice, uppercase text in white, and a minimalistic design.

Expert Tips for CSS nth-child Element Selection

Tired of selecting elements one by one in your CSS code? Discover the magic of CSS nth-child!

by Mar 17, 2023UX/UI

Home / UX/UI / Expert Tips for CSS nth-child Element Selection

CSS is at the heart of every great web experience. From layouts to color palettes, it gives a page its personality. But if you want your designs to stand out (and keep your code clean), you need to move beyond the basics. One of the most versatile selectors in your CSS toolkit is nth-child.

The nth-child selector lets you target and style specific elements based on their position within a parent. It accepts an expression as an argument, giving you the power to create dynamic, scalable layouts without extra markup. Here’s how it works—with a little help from the animal kingdom.

🐶 First Things First

The early bird may get the worm—but this pup gets your attention.

To select the first item in a group, use:

:first-child

🐈 Last But Not Least

This kitty knows the value of a dramatic exit.

To style the last element, try:

:last-child

🐘 Better Last Than Second-Last?

Second-to-last might not sound glamorous, but this elephant disagrees.

To style the second-last item, use:

:nth-last-child(2)

🐼 The Unsung Math Heroes: Even Elements

Even numbers bring balance, and these pandas know it.

To target even-positioned elements:

:nth-child(even)

🌵 Spot the Odd One Out

Odd numbers shake things up—and so do these quirky cacti.

To style odd-numbered elements:

:nth-child(odd)

🌴 May the Fourth Be With You

Palm trees bend, not break—just like this handy selector.

To target every fourth element, offset by 7:

:nth-child(4n - 7)

🦖 Give Me Five!

High five to these speedy T-Rexes.

To select the first five elements, go with:

:nth-child(-n+5)

🦁 All But the First Five

Lions don’t wait around. Neither should your styles.

To select everything starting from the sixth element:

:nth-child(n+6)

🐨 Leeloo’s Element (Yes, That One)

A subtle nod to 90s sci-fi, but today the 5th element is a sweet koala.

To select the fifth element:

:nth-child(5)

Wrapping Up

With nth-child, you can write cleaner code and apply smarter styling. Whether you’re working on grids, lists, or reusable UI components, this selector gives you precise control—no extra classes required.

Want to keep leveling up your frontend skills? Don’t miss our article on UI design do’s and don’ts, packed with practical advice to help you design with both beauty and usability in mind.