Today weβll be learning some CSS basics. I tend to use nth-child CSS selectors in my articles.
But that made me realize I havenβt gone over the basics of using nth-child selectors.
Today we will be exploring the options of this powerful CSS selector with some examples.
Nth-child basic selectors
Letβs start with some basic nth-child selectors:
We can define which number of an element we want to select. So letβs say we want to select the third list element.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
li:nth-child(3) {
color: green;
}
The result is that only the third element is selected for the styles:
Odd/Even selector
We can select every odd or even element number by using these attributes.
li:nth-child(odd) {
color: red;
}
The result is that only the odd items are selected:
li:nth-child(even) {
color: blue;
}
In this example, the selector takes all even HTML elements and applies the styling:
Every x selector
Something cool we can do with the nth-child selector is select every x element. So letβs say, for example we want every fourth element:
li:nth-child(4n) {
color: purple;
}
Now every 4th child element is selected:
Or if we want to include the first item:
li:nth-child(4n + 1) {
color: purple;
}
Result:
We can also start from the second element, for instance:
li:nth-child(4n + 2) {
color: purple;
}
Result:
Select every item but the first x items
We can even use a selector that selects every tag but the first three elements.
li:nth-child(n + 4) {
color: teal;
}
Result:
Select first x number of elements
Another cool thing we can do is select only the first x amount. Letβs get the first three items:
li:nth-child(-n + 3) {
color: teal;
}
Result:
Select the last element
We can even select the last element.
li:last-child {
color: orange;
}
Result:
We can also offset to get the second to last list item.
li:nth-last-child(2) {
color: orange;
}
Result:
Combining selectors
We can also combine nth-child selectors!
Letβs say you want to get every even number from an odd list amount.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
ul:nth-child(odd) li:nth-child(even) {
color: orange;
}
This will get all the odd ul
and then all the even li
tags.
Result:
See all examples in this Codepen to try it out
Have a play around with this Codepen. Try and change some selectors to see what happens!
See the Pen CSS nth-child selector basics by Chris Bongers (@rebelchris) on CodePen.
Browser Support for nth-child selectors
The nth-child selector has excellent support and can be used in most browsers. Donβt hesitate to make use of them.
Thank you for reading, and letβs connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter