:first-child (CSS selector)

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
}

Learn HTML5 Online

Get all SitePoint books and courses with a Learnable membership. Start building future-proof websites that are faster, more powerful, and easier to maintain.

No Reader comments

Comments on this post are closed.