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 :nth-last-of-type(n) Selector
The CSS :nth-last-of-type(n) selector targets elements based on their position among siblings of the same type, counting from the last element backwards. It's particularly useful for styling specific elements without adding classes or IDs.
Syntax
:nth-last-of-type(n) {
/* CSS properties */
}
Possible Values
| Value | Description |
|---|---|
number |
Selects the nth element from the end (1, 2, 3, etc.) |
even |
Selects even-positioned elements from the end |
odd |
Selects odd-positioned elements from the end |
formula |
Uses expressions like 2n+1, 3n, etc. |
Example: Selecting Second Last Element
The following example selects the second last paragraph element and applies blue background −
<!DOCTYPE html>
<html>
<head>
<style>
p:nth-last-of-type(2) {
background: blue;
color: white;
padding: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<p>This is demo text 1.</p>
<p>This is demo text 2.</p>
<p>This is demo text 3.</p>
<p>This is demo text 4.</p>
<p>This is demo text 5.</p>
</body>
</html>
Five paragraphs appear with "This is demo text 4" (the second last paragraph) highlighted with a blue background, white text, padding, and rounded corners.
Example: Using Formula (2n)
This example demonstrates selecting every second element from the end using a formula −
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: 5px;
padding: 15px;
border: 1px solid #ccc;
}
div:nth-last-of-type(2n) {
background-color: #f0f8ff;
border-color: #4169e1;
}
</style>
</head>
<body>
<div>Box 1</div>
<div>Box 2</div>
<div>Box 3</div>
<div>Box 4</div>
<div>Box 5</div>
<div>Box 6</div>
</body>
</html>
Six boxes appear where Box 2, Box 4, and Box 6 (every second element counting from the end) have light blue backgrounds and blue borders.
Conclusion
The :nth-last-of-type(n) selector provides flexible element selection by counting backwards from the last sibling of the same type. It's ideal for creating alternating patterns or targeting specific elements without modifying HTML structure.
Advertisements
