CSS :last-child

The CSS :last-child pseudo-class selects the last child element of its parent element. For example, the following CSS code applies style to all P that are the last child of their parent element:

p:last-child {background-color: purple; color: white; padding: 8px;}

CSS :last-child syntax

The syntax of the ":last-child" pseudo-class in CSS is as follows:

parent-selector:last-child {
   // CSS styles
}

The parent-selector is the selector for the parent element, and :last-child is the pseudo-class selector.

CSS :last-child Example

Consider the following code as an example demonstrating the ":last-child" pseudo-class in CSS:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:last-child {font-weight: bold; color: orchid;}
   </style>
</head>
<body>

   <p>This is para one.</p>
   <p>This is para two.</p>
   <div>
      <p>This is para one, inside DIV.</p>
      <p>This is para two, inside DIV (the last para of DIV).</p>
   </div>
   <p>This is para three.</p>
   <p>This is para four (the last para of BODY).</p>
   
</body>
</html>
Output

This is para one.

This is para two.

This is para one, inside DIV.

This is para two, inside DIV (the last para of DIV).

This is para three.

This is para four (the last para of BODY).

In the CSS styles, we have defined a selector p:last-child which selects the last child p element of its parent element. This selector applies the font-weight: bold; and color: orchid; properties to the last child p element.

In the HTML body, we have multiple p elements inside different parent elements. The first and second p elements are siblings, and the second one is the last child of its parent, which is the body element. Therefore, the CSS selector p:last-child applies the defined styles to the second paragraph, and it will appear in bold font-weight and orchid color.

The third and fourth p elements are nested inside a div element, and the last p element is the last child of the div element. Hence, the CSS selector p:last-child also applies the defined styles to the fourth paragraph, and it will also appear in bold font-weight and orchid color.

Therefore, the output of this code would be two paragraphs (the second and fourth) with bold font-weight and orchid color.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!