CSS Solid

Pseudo-Class - :first-child

Selects first child element under the parent element when first child element is a specified element.

Example:

p:first-child {
   background-color:lightgreen;
}

Above example sets background color (light green) to first child element under the parent element when first child element is a P element.

Example 1) Set background color (light green) to first child under each parent element when first child element is a P element.

<!DOCTYPE HTML>
<html>
<head>
    <title> CSS pseudo-class selector - :first-child</title>
     <style>
            p:first-child
            {
                background-color:lightgreen;
            }
     </style>
</head>
<body>
    <p>1st child(P) of the parent (BODY)</p>

    <div>
        <p> ----- 1st child(P) of the parent (DIV) </p>
        <p> ----- 2nd child(P) of the parent (DIV) </p>
    </div>

    <div>
        <span> 1st child(SPAN) of the parent (DIV) </span>
        <p> 2nd child(P) of the parent </p>
    </div>
</body>
</html>

Result:

In the above example,

  • P element is first child of BODY and DIV parent elements. So background color “lightgreen” is set to these two elements.
  • SPAN element (not P element) is first child of second DIV parent element. So no background color is set to this element.

Using following Document Object Model (DOM) tree, above example is explained.

Example 2:

<!DOCTYPE html>
<html>
<head>
    <title> CSS pseudo-class selector - :first-child </title>
    <style type="text/css">
        p:first-child {
            background-color: lightgreen;
        }
    </style>
</head>
<body>
    <div >
        <p> -- Child (DIV - P)  </p>
        <p> -- Child (DIV - P) </p>
        <div>
            <p> -------- Grandchild (DIV - DIV - P) </p>
            <p> -------- Grandchild (DIV - DIV - P) </p>
            <div>
                <p> ---------------- Great-grandchild  (DIV - DIV - DIV - P)</p>
            </div>
        </div>
    </div>
    <div>
        <p> -- Child (DIV - P)</p>
    </div>
    <p>P element </p>
    <p>P element </p>
</body>
</html

Result:

Above example sets font background color green to first child element under each parent (DIV) element.

Using following Document Object Model (DOM) tree, above example is explained.