I made a neat discovery while working on a project last week: it’s easy to override previously defined :nth-of-type
pseudo-classes with :nth-of-type(n)
. For example, consider the following CSS:
li:nth-of-type(1) {
margin-top: 10px;
}
li:nth-of-type(2) {
margin-top: 20px;
}
li:nth-of-type(3) {
margin-top: 30px;
}
li:nth-of-type(4) {
margin-top: 40px;
}
The above will apply margin-top: 10px;
to the first list-item, margin-top: 20px;
to the second list-item, margin-top: 30px;
to the third list-item, and margin-top: 40px;
to the fourth list-item.
Why would someone want to do that,
you ask. I don’t know, this is a simplified demo,
I answer. Then we hug.
Later, something requires those list-items to be overridden with a new rule. That something can be a media query (for example: when the viewport gets wider, the list-items’ margin-top
should reset to 0
), or it could be a modifier class added by an event (for example: when a visitor clicks a button, the list-items’ margin-top
should become 50px
), etc. The something doesn’t really matter, what matters is how easy it is to apply an overriding rule:
li:nth-of-type(n) {
margin-top: 0;
}
Passing the letter n
to :nth-of-type
is CSS’s way of saying, Just select every list-item
, and when used the way we’ve used it in this article, it tells the web browser to override the rules we defined earlier.
How neat is that?