CSS Solid

Pseudo-Class - :last-child

Selects the last child element of parent element when last child element is a specified element.

Example:

p:last-child {
  color: red;
}

Above example sets text color (red) to the last child element of parent element when last child element is a P element.

Example: Set text color (red) to the last child of each parent element when last child element is a P element.

<!DOCTYPE HTML>
<html>
<head>
    <title> CSS pseudo-class selector - :last-child</title>
    <style>
        p:last-child {
            color: red;
        }
    </style>
</head>
<body>
    <p>1st child(P) of the parent (BODY)</p>
    <div>
        <p> ----- 1st child(P) of the parent (DIV 1) </p>
        <p> ----- 2nd child(P) of the parent (DIV 1) </p>
    </div>
    <div>
        <p> -----  1st child(P) of the parent (DIV 2) </p>
        <span> -----  2nd child(SPAN) of the parent (DIV 2) </span>
    </div>
    <p>Last child(P) of the parent (BODY)</p>
</body>
</html>

Result:

In the above example,

  • P element is the last child element of BODY and first DIV parent elements. So text color “red” is set to these two elements.
  • SPAN element (not P element) is the last 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.