A guide to :nth-child
This is a pseudo-class that I end up using a lot, so I decided to share how to use it and how I incorporate it in my themes!
Let’s start off by explaining what a pseudo-class is. A pseudo-class is something you add to a selector to style it for a specific state. :hover is probably the one I see the most, which is used to style an element when the mouse hovers over it.
:nth-child and its related classes (nth-of-type, first-child, last-child, etc), let you style an element based on its order. This is especially useful for styling lists. This is also how I positioned the individual posts for my honeycomb theme.
Here’s how to use it!
Let’s say we want to take this list:
<li> one </li>
<li> two </li>
<li> three </li>
<li> four </li>
<li> five </l>
and make only the second item have a blue background.
After the css for the list, we would add new styling for li:nth-child(2), which will look like this:
background: cornflowerblue; /* this is just one of my favorite blues*/
Now we can do the same for any number in the list too, like :nth-child(3) would be the third item, and :nth-child(4) would be the fourth. If we wanted to do the first or last item, a better option would be :first-child and :last-child
If you wanted to make every third item blue, you would use :nth-child(3n).
so changing the CSS to this (and adding another list item in the html)
will look like this:
More formula examples and explanations under the cut!