:first-child and :last-child
Learn :first-child and :last-child pseudo-classes.
What is :first-child?
The :first-child pseudo-class selects the element that is first among its siblings. It is equivalent to :nth-child(1) but reads better.
For example, li:first-child grabs the very first item in a list. To give a different style to the first link in a menu, use nav a:first-child.
This pseudo-class saves you from adding a class when position alone is meaningful.
What is :last-child?
:last-child selects the element that is last among its siblings. It is the mirror of :first-child.
In a horizontal menu, nav a:last-child lets you drop the separator line after the final link. Again, no class is needed; you target by position alone.
If the element is alone — no other siblings — it counts as both first and last; both pseudo-classes match.
Margin and separator patterns
:first-child and :last-child are mostly used to fix margins and separators. If every item in a card list gets margin-left, the first one shifts too; you cancel it with :first-child { margin-left: 0; }.
Likewise, if you put a border-right between links, the last link carries an extra one; :last-child removes it. This pattern keeps flexible lists tidy.
Exercise Style the first and last links of a menu
Write two declarations. First, a nav a:first-child selector with font-weight: bold inside. Second, a nav a:last-child selector with border-right: none inside. Both should sit in their own { } block.
Show example solution
/* add styles for the first and last menu links */
nav a:first-child {
font-weight: bold;
}
nav a:last-child {
border-right: none;
}
Test yourself
-
What does li:first-child match?
li:first-child { font-weight: bold; }- The last item in the list
- The item with the 'first' class
- Every item in the list
- The first item in the list
Show answer
The first item in the list — Correct. :first-child selects the first sibling.
-
Write the selector for the last link of the menu
nav a____ { border-right: none; }Show answer
nav a:last-child { border-right: none; } -
Match each pseudo-class to its position
- :first-child
- First sibling
- :last-child
- Last sibling
- :nth-child(2)
- Second sibling
- :nth-child(even)
- Even positions