CSS Pseudo-classes
A pseudo-class is a keyword added to a selector that picks elements by state or position. Siblings are elements that share the same parent.
Make the first item bold
The first-child pseudo-class picks the first item in the list.
li:first-child {
font-weight: bold;
}Colour the last item
The last-child pseudo-class picks the last item in the list.
li:last-child {
color: red;
}Stripe the even table rows
The header row is child 1 of the table rows. The Ana row is child 2, so the even rule matches it.
tr:nth-child(even) {
background-color: yellow;
}Example
li:first-child {
font-weight: bold;
}
li:last-child {
color: red;
}
li:nth-child(2) {
color: blue;
}
tr:nth-child(even) {
background-color: yellow;
}Key points
- Counting for nth-child starts at 1, not at 0.
- A formula like 2n matches every second child.
- The selector :root names the html element, the root of the page.
- A pseudo-class narrows a selector to elements in a chosen position.
In this example, the first list item is made bold. The last list item is coloured red. The second list item is coloured blue. The even table rows get a yellow background. The Ana row is the second row, so it shows the stripe.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which pseudo-class picks the first item in a list?