CSS :first-child

The :first-child CSS pseudo-class represents the first element among a group of sibling elements. It targets an element that is the first child of its parent element.

Let's take a look at how to use the :first-child pseudo-class with some examples:

Result:

    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>

    <style>
      li:first-child {
        color: red;
      }
    </style>
  
  • Item 1
  • Item 2
  • Item 3

In the example above, we have an unordered list (<ul>) with three list items (<li>). We apply the :first-child pseudo-class to the <li> element to change the color of the first item to red.

Here's another example using different HTML elements:

Result:

    <div>
      <p>First paragraph</p>
      <p>Second paragraph</p>
      <span>First span</span>
    </div>

    <style>
      div>p:first-child {
        font-weight: bold;
      }
    </style>
  

First paragraph

Second paragraph

First span

In this example, we have a <div> element containing two paragraphs and a <span> element. We use the :first-child pseudo-class to make the first paragraph bold.

By using the :first-child pseudo-class, you can target specific elements within a group of siblings and apply different styles or effects to them.