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
Role of CSS :nth-last-child(n) Selector
The CSS :nth-last-child(n) selector targets elements based on their position among siblings, counting backwards from the last child. This pseudo-class is useful for styling specific elements when you know their position from the end of a container.
Syntax
selector:nth-last-child(n) {
property: value;
}
Where n can be a number, keyword, or formula (odd, even, 2n+1, etc.).
Possible Values
| Value | Description |
|---|---|
number |
Selects the nth element from the end (1-indexed) |
odd |
Selects odd-positioned elements from the end |
even |
Selects even-positioned elements from the end |
formula |
Uses mathematical expression like 2n+1, 3n, etc. |
Example: Selecting Specific Position
The following example styles the 4th paragraph from the last (3rd paragraph in this case) −
<!DOCTYPE html>
<html>
<head>
<style>
p {
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
}
p:nth-last-child(4) {
background: blue;
color: white;
font-weight: bold;
}
</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>
<p>This is demo text 6.</p>
</body>
</html>
Six paragraphs appear with borders. The 3rd paragraph (4th from the end) has a blue background with white, bold text, while others have the default styling.
Example: Using Keywords
This example demonstrates styling odd-positioned elements from the end −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
flex-direction: column;
gap: 10px;
}
.item {
padding: 15px;
background-color: #f0f0f0;
border-radius: 5px;
}
.item:nth-last-child(odd) {
background-color: #ff6b6b;
color: white;
}
</style>
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
</div>
</body>
</html>
Five items appear in a column. Items 1, 3, and 5 (odd positions from the end) have red backgrounds with white text, while items 2 and 4 have gray backgrounds.
Conclusion
The :nth-last-child(n) selector provides flexible targeting of elements based on their reverse position. It's particularly useful for styling last few elements or creating alternating patterns from the end of a container.
