CSS :nth-last-child Pseudo Class
The:nth-last-child() pseudo-class selects elements based on their index starting from the last element upwards.
The:nth-last-child() can be specified by a number, a keyword, or a formula.
Keyword values¶
odd¶
Selects elements with odd index numbers (e.g 1, 3, 5, 7 etc.).
even¶
Selects elements with even index numbers (e.g 2, 4, 6, 8 etc.).
Functional notation¶
<An+B>¶
Selects elements whose numeric position matches the pattern An+B (for every positive integer or zero value of n). The first element’s index is 1, and n in the formula starts from 0. The values A and B must be integers.
Version ¶
Selectors Level 4
Selectors Level 3
Syntax¶
:nth-last-child() {
css declarations;
}
Example of the :nth-last-child() selector:¶
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:last-child {
background-color: #1c87c9;
color: #fff;
}
</style>
</head>
<body>
<h2>:nth-last-child selector example</h2>
<p>Lorem ipsum is simply dummy text...</p>
<p>Lorem Ipsum is simply dummy text...</p>
</body>
</html>
Example of "odd" and "even" keywords:¶
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:nth-last-child(odd) {
background: #1c87c9;
color: #eee;
}
p:nth-last-child(even) {
background: #666;
color: #eee;
}
</style>
</head>
<body>
<h2>:nth-last-child selector example</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
</body>
</html>
Example of :nth-last-child() with the <table> tag:¶
<!DOCTYPE html>
<html>
<head>
<style>
table {
border: 1px solid #8EBF41;
border-spacing: 10px;
font-family: sans-serif;
}
table tr {
background-color: #cccccc;
}
/* Selects the last three elements */
tr:nth-last-child(-n+3) {
background-color: #8EBF41;
}
table tr td {
padding: 10px;
}
/* Selects every element starting from the second to last item */
tr:nth-last-child(n+2) {
color: #ffffff;
}
/* Select only the last second element */
tr:nth-last-child(2) {
font-weight: 900;
}
</style>
</head>
<body>
<h2>:nth-last-child selector example</h2>
<table>
<tbody>
<tr>
<td>First row</td>
</tr>
<tr>
<td>Second row</td>
</tr>
<tr>
<td>Third row</td>
</tr>
<tr>
<td>Fourth row</td>
</tr>
<tr>
<td>Fifth row</td>
</tr>
</tbody>
</table>
</body>
</html>
Example of :nth-last-child() with the <li> tag:¶
<!DOCTYPE html>
<html>
<head>
<style>
/* If there are at least three list items, style them all */
li:nth-last-child(n+3),
li:nth-last-child(n+3) ~ li {
color: #8EBF41;
}
</style>
</head>
<body>
<h2>:nth-last-child selector example</h2>
<ol>
<li>List Item One</li>
<li>List Item Two</li>
</ol>
<ol>
<li>List Item One</li>
<li>List Item Two</li>
<li>List Item Three</li>
<li>List Item Four</li>
<li>List Item Five</li>
<li>List Item Six</li>
</ol>
</body>
</html>
0 Comments
CAN FEEDBACK
Emoji