The :nth-last-child(n) CSS pseudo-class selector targets specific elements based on their position relative to the end of their parent element’s child list.
Syntax
element:nth-last-child(n) {
/* styles */
}
Breaking Down the ‘n’ Parameter
The n parameter can be a variety of values:
- Number: Selects the nth child from the end.
li:nth-last-child(2) {
/* Styles the second-to-last list item */
}
- Keyword
odd: Selects odd-numbered children from the end.
li:nth-last-child(odd) {
/* Styles odd-numbered list items from the end */
}
- Keyword
even: Selects even-numbered children from the end.
li:nth-last-child(even) {
/* Styles even-numbered list items from the end */
}
- Formula: Uses a formula to select elements based on a pattern.
li:nth-last-child(3n) {
/* Styles every third child from the end */
}
Example
Let’s say you have a navigation menu with multiple items, and you want to style the last two items differently:
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Services</li>
<li>Contact</li>
</ul>
</nav>
nav ul li:nth-last-child(2),
nav ul li:nth-last-child(1) {
background-color: #f0f0f0;
border-radius: 5px;
}
This CSS will style the second-to-last and last list items with a light gray background and rounded corners.
Key Points
- Specificity: Remember that CSS specificity rules apply to these selectors. More specific selectors will override less specific ones.
- Combinations: You can combine
:nth-last-child()with other selectors to create complex styles. - Browser Compatibility: While most modern browsers support
:nth-last-child(), older browsers may have limited support. Consider using a CSS preprocessor or a polyfill for wider compatibility.