CSS Pseudo-Classes (including :nth-child)
A highly effective, and fairly straight-forward, way to make your pages look better is by using CSS pseudo-classes (or pseudo-selectors).
Pseudo-classes specify a special state of a selected element. It’s kind of like CSS’s version of an event listener. You can define a pseudo-class for when a user hovers over something, visits a link from your page, “focuses” on an element, and much more. We’re going to cover the basic pseudo-classes, but you can find a complete index of pseudo-classes here: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes.
Pseudo-classes are easy to implement into your code. The syntax is as follows:
selector:pseudo-class {
property: value;
}
For example, let’s say you want to have a button (.dropdownButton) highlight gray when a user hovers over it:
.dropdown-button:hover{
background-color: lightgray;
}
Using pseudo-classes to select specific children
You can use pseudo-classes to select certain children as well. First-child, last-child, first-of-type, and nth-child are a few, but not all, of the pseudo-classes for selecting certain children. This uses the same pseudo-class syntax as above, so to select the first child or a certain class, you’d just do something like:
.class:first-child {
color: orange;
}
nth-child()
A more specific way to select certain children is using nth-child. N is represented by a single argument, and it can be either a number, a keyword, or a formula.
For example, if you wanted to select the third element of parent, you’d just put 3 in as your nth-child argument, like so:
.class:nth-child(3) {
color: orange;
}
You can also select multiple children. If you want to select every third child, you’d just put 3n in your argument:
.class:nth-child(3n) {
color: orange;
}
Or, you can use a keyword like even or odd in your argument to select all even (or odd) children:
.class:nth-child(even) {
color: orange;
}
Finally, there is a formula that allows you to be even more specific with your selectors. The formula is An + B, where:
- A is the cycle size
- N is the counter which starts at 0
- B is the amount of offset (or where the formula will start).
So if you want to select every element, starting at the sixth child, you’d write:
.class:nth-child(n + 6) {
color: orange;
}
Or if you wanted every third element starting at the fourth child:
.class:nth-child(3n + 4) {
color: orange;
}
CSS pseudo-classes are useful and fairly straightforward. The simple logic and syntax allow for easy implementation, and there is a mini laundry list of available pseudo-classes to use.