Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Role of CSS :last-of-type Selector
The CSS :last-of-type selector targets the last element of its type among siblings within the same parent element. It's particularly useful for styling the final occurrence of specific HTML elements without needing to add classes or IDs.
Syntax
element:last-of-type {
property: value;
}
Example: Basic Usage
The following example applies an orange background to the last paragraph element −
<!DOCTYPE html>
<html>
<head>
<style>
p:last-of-type {
background-color: orange;
padding: 10px;
margin: 10px 0;
}
p {
background-color: #f0f0f0;
padding: 10px;
margin: 10px 0;
}
</style>
</head>
<body>
<h2>Heading</h2>
<p>This is demo text1.</p>
<p>This is demo text2.</p>
<p>This is demo text3.</p>
<div>This is a div element</div>
</body>
</html>
Three paragraphs appear with gray backgrounds. The last paragraph (text3) has an orange background, while the first two paragraphs maintain their gray background.
Example: Multiple Element Types
This example demonstrates how :last-of-type works with different element types −
<!DOCTYPE html>
<html>
<head>
<style>
h3:last-of-type {
color: red;
border-bottom: 2px solid red;
}
span:last-of-type {
background-color: yellow;
font-weight: bold;
}
div {
margin: 15px 0;
padding: 10px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div>
<h3>First Heading</h3>
<h3>Second Heading</h3>
<h3>Last Heading</h3>
<span>First span</span>
<span>Second span</span>
<span>Last span</span>
</div>
</body>
</html>
A container with three headings and three spans appears. The last heading (h3) is styled in red with a red underline, and the last span has a yellow background with bold text.
Conclusion
The :last-of-type selector provides precise control over styling the final element of each type, making it valuable for creating clean layouts without additional markup. It works independently for each element type within the same parent.
Advertisements
