CSS :last-of-type
selector selects every element that is the last element of its type within its parent element. This last element can be of any type, like a <p>
, <div>
, <li>
, <ul>
etc.
Unlike the :last-child selector, the :last-of-type
selector targets the last element of its type regardless of its occurrence within its parent.
This means that the target element needs not to be the last child of its parent. It could be the second, third or fourth child of its parent but must be the last element of its type.
In the following example, the p:last-of-type
selector selects the last element of type <p>
within its parent and sets a yellow background color to it.
Example:
p:last-of-type{ background-color: yellow; }
If we take the above example and use p:last-child
instead of p:last-of-type
, it would not select any element. This is because the p:last-child selector targets all the <p> elements which are the last child of their container.
But, in our case, the <h3> element is the last child its parent(<body>
) and it is of type <h3> not <p>. Therefore, no element wil be selected.
Here is the same example as above but with the :last-child
selector:
Example:
p:last-child{ background-color: yellow; }
Select Nested Elements with :last-of-type Selector
With the :last-of-type
selector, we can also target the nested elements of a specific type.
To do that we have to simply put a space between the parent element and the :last-of-type selector.
For example, if you want to select the last element(s) of type <p> which is inside a <div> element, you have to use div p:last-of-type
.
Here is a working example:
Example:
div p:last-of-type{ background-color: yellow; }
If you do not specify the type of the nested element, the last element of each type will be selected.
See this example:
Example:
div :last-of-type{ background-color: yellow; }
CSS Syntax
The syntax of the :last-of-type
selector is as follows:
:last-of-type{ CSS Styles; }
Browser Support
The number in each cell of the table specifies the first version of the browser that fully supports the :last-of-type
selector.
Selector | |||||
:last-of-type | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |