Difference Between

first-child and first-of-type

The :first-child CSS pseudo-class represents the first element among a group of sibling elements.

The :first-of-type CSS pseudo-class represents the first element of its type among a group of sibling elements.

Children are same type

<div>
  <p></p>
  <!-- p:first-child, p:first-of-type -->

  <p></p>
</div>

Children are different types

<div>
  <h1></h1>
  <p></p>
  <!-- p:first-of-type -->

  <p></p>
</div>

Examples

Using :first-child

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>First Child</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      p:first-child {
        color: red;
      }
    </style>
  </head>
  <body>
    <div>
      <p>This text is selected!</p>
      <p>This text isn't selected.</p>
    </div>

    <div>
      <h2>This text isn't selected: it's not a "p".</h2>
      <p>This text isn't selected.</p>
    </div>

  </body>
</html>

Using :first-of-type

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>First Child</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      p:first-of-type {
        color: red;
      }
    </style>
  </head>
  <body>
    <div>
      <p>This text is selected!</p>
      <p>This text isn't selected.</p>
    </div>

    <div>
      <h2>This text isn't selected: it's not a "p".</h2>
      <p>This text isn't selected.</p>
    </div>

  </body>
</html>

Select first-child whatever type they are

Imagine a case you want to select the first child of whatever type they might be, you can use this:

.parent :first-child {
  color: red;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>First Child</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      .parent :first-child {
        color: red;
      }
    </style>
  </head>
  <body>
    <div class="parent">
      <p>This text is selected!</p>
      <p>This text isn't selected.</p>
    </div>

    <div class="parent">
      <h2>This text isn't selected: it's not a "p".</h2>
      <p>This text isn't selected.</p>
    </div>

  </body>
</html>
Last Update: 12:13 - 22 April 2024

On this page