Skip to main content

:first-child (CSS selector)

By Adam Roberts

HTML & CSS

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Description

This pseudo-class matches an element only if it’s the first child element of its parent element. For instance, li:first-child matches the first list item in an ol or ul element. It doesn’t match the first child of a list item.

For example, let’s take the CSS selector mentioned above:

li:first-child {
  ⋮ declarations
}

And let’s apply it to the following markup:

<ul>
  <li>This item matches the selector li:first-child.</li>
  <li>This item does not match that selector.</li>
  <li>Neither does this one.</li>
</ul>

Only the first list item element is matched.

Note that this pseudo-class only applies to elements—it doesn’t apply to anonymous boxes generated for text.

Example

This example selector matches the
first list item in an ol or ul
element:

li:first-child {
  ⋮ declarations
}

Adam is SitePoint's head of newsletters, who mainly writes Versioning, a daily newsletter covering everything new and interesting in the world of web development. He has a beard and will talk to you about beer and Star Wars, if you let him.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.