CSS :last-of-type

The CSS :last-of-type pseudo-class is used when we need to select the last child element of a specified element type of their parent.

For example, the following CSS code applies the style to the last child element of type P of their parent:

p:last-of-type {background-color: #ccc; padding: 8px; border: 3px solid green;}

CSS :last-of-type syntax

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

selector:last-of-type {
   // CSS styles
}

In this case, selector is the element to be selected, and :last-of-type is the selector that matches the element that is the last of its type among its siblings.

CSS :last-of-type Example

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

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:last-of-type {background-color: plum; padding: 10px;}
   </style>
</head>
<body>

   <p>This is para one.</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 two.</p>
   <p>This is para three (the last para of BODY).</p>
   
</body>
</html>
Output

This is para one.

This is para one, inside DIV.

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

This is para two.

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

In the above example, the CSS code inside the "style" tags will select the last p element of each type that is a sibling of its own type and apply a background color of "plum," and padding of 10 pixels.

Specifically, the selector p:last-of-type matches the last p element of its type among its siblings. So in this case, it will match the last p element before the div, the last p element inside the div, and the last p element in the body.

The first p element ("This is para one.") is not affected because it is not the last p element of its type among its siblings. The second p element inside the div ("this is para two, inside DIV (the last para of DIV).") is affected because it is the last p element inside the div. The third p element ("This is para two.") is not affected because it is not the last p element of its type among its siblings. The fourth p element ("This is para three (the last para of BODY).") is affected because it is the last p element in the body.

So, the result will be that the background color of the second and fourth p elements will be "plum" and they will have a padding of 10 pixels.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!