X

Headline

This is an important message requiring you to make a choice if you're based in the EU.

CSS :first-child Pseudo Class

The :first-child CSS pseudo-class selects the element if it is the first child among other elements.

The :first-of-type selector can be used if the user wants to select and apply the style on the first paragraph whether or not it is the first child.

Version

CSS2

Syntax

:first-child {
css declarations;
}

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p:first-child {
      background-color: #1c87c9;
      color:#fff;
      }
    </style>
  </head>
  <body>
    <p>Lorem ipsum is simply dummy text...</p>
    <h2>First-child selector example</h2>
    <p>Lorem Ipsum is simply dummy text...</p>
  </body>
</html>

Another example with the :first-child selector:

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      li:first-child {
      background: #8ebf42;
      } 
    </style>
  </head>
  <body>
    <h2>:first-child selector example</h2>
    <ul>
      <li>Paris</li>
      <li>Moscow</li>
      <li>Rome</li>
    </ul>
    <ol>
      <li>Paris</li>
      <li>Moscow</li>
      <li>Rome</li>
    </ol>
  </body>
</html>

Browser support

4.0+ 12.0+ 2.0+ 3.1+ 10.0+

Practice Your Knowledge

The :first-child CSS pseudo-class selects the element if



Do you find this helpful?

Related articles