Using CSS :first-child / :last-child

The CSS selectors :first-child and :last-child are used to apply CSS styling to the first, or last element that is a child of the parent.

For example, if you have the following list:

<ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
    <li>Forth</li>
</ul>

You could give the first element a light blue background with CSS:

li {
    background-color: lightgray;
}
li:first-child {
    background-color: lightblue;
}

Displayed as:

  • First
  • Second
  • Third
  • Forth

Using :first-child / :last-child instead of CSS classes

It’s quite common to find CSS classes added to elements to indicate they are the first or last item in a group. This may be because the design requires margins or borders are to be handled differently for the elements at the edge. The CSS classes used for this are often given names like alpha, omega, first, or last. For example:

<ul>
    <li class="first">First</li>
    <li>Second</li>
    <li>Third</li>
    <li class="last">Forth</li>
</ul>

This allows us to style the first and last elements differently, as required. However in CSS3, we can use :first-child and :last-child to handle many of the cases in which those classes are used. This means we don’t need to add in those extra classes to the HTML code, which is useful as it helps keep the HTML code cleaner. It also allows us to more easily style HTML that’s generated by parts of the code we my not easily have direct control over, such as 3rd party libraries, or plugins.

If we wanted to put a dividing line between the list items, such as:

li {
    border-right: 1px solid gray;
}

But didn’t want the border at the end, after the last element, we could use:

li:last-child {
    border-right: none;
}

Instead of:

li.last {
    border-right: none;
}

Displayed as:

  • First
  • Second
  • Third
  • Forth

Taking it further

There’s also a few other related CSS Selectors, such as :nth-child(n) which can be be used to select elements based on other criteria, such as being the nth child element.

These selectors are available in any modern browser, and from IE9 onwards.

If you enjoyed this post, consider leaving a comment or subscribing to the RSS feed.
This site uses cookies. Find out more about cookies.