Better Programming

Advice for programmers.

Follow publication

Member-only story

Introduction to nth-child CSS Selector

Code & Coins
Better Programming
Published in
6 min readSep 10, 2019

--

Photo by Greg Rakozy on Unsplash

nth-child is a selector that matches every nth child element of its parent. Say you want to apply CSS to only a specific number of p elements. nth-child is exactly what you need.

#nameContainer p {
color: black;
}
#nameContainer:hover p:nth-child(1) {
color: red;
}

The above CSS will change the color of only the first p when the user hovers over nameContainer.

Other Options That Can Be Passed to nth-child

odd

By using nth-child(odd), you can apply CSS to every odd child element. If you were to rewrite the CSS above to affect every odd element, the p tag for Kelly, Stanley, Michael, and so on would turn red.

even

Conversely, nth-child(even) would apply CSS to Creed, Oscar, Jim, etc.

formula (an + b)

In addition to the value n being able to be any number, you can also use a formula. nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one. Multiplication and division are not supported in nth-child(n) formulas. Let’s break down this formula format and see what each part means to nth-child.

a represents the cycle size. If a is equal to 3, that means that the CSS is applied to every third element. See below for p:nth-child(3n).

n is the counter used to determine which sibling element among the group is affected. By itself, it refers to every child element. p:nth-child(n) would select every p. This is a bit redundant as you could simply use p by itself.

b represents the offset value. If you look back to the earlier example nth-child(3n+1), the CSS would be applied to every third element…

--

--

Code & Coins
Code & Coins

Written by Code & Coins

Blogging about software 👨🏻‍💻 and money 💰 https://linktr.ee/mattcroak

Responses (2)

Write a response