Using CSS nth-child Selector

CSS’s nth-child selector is a very useful tool that allows you to single out only certain html elements to style without having to add any class or id tags. The selector targets every element that is the nth child of a given parent element. For example, if you want to style only the third child of every paragraph so that its background color is yellow, the syntax would appear as follows:

p:nth-child(3){

background-color: yellow;

}

This will style the third child of every paragraph so that the background is yellow, regardless of what type of html element that child is. You can also use this selector to style all the odd-numbered children (for example the first, third, and fifth children, etc) of a paragraph parent element, by making the parameter “odd.” The syntax would look like this:

Join us in our newest publication:
p:nth-child(odd){

background-color: yellow;

}

To select even-numbered children, use the word “even” instead. This selector also allows you to target children of a parent element using the formula an + b as a parameter, where a and b are integers, and n is a counter that starts at zero. If you want to target every third child of a paragraph, the syntax could look like this:

p:nth-child(3n+0){

background-color: yellow;

}

Because n increases by one with each cycle, the elements that will be targeted are the 3rd, 6th, 9th, etc, children of the parent.

Share and Enjoy !

0Shares
0 0