:nth-last-child CSS Pseudo Class
Description
The CSS :nth-last-child
pseudo-class is a powerful selector that allows you to target and style elements based on their position within a parent element, counting from the end of the parent's list of children. It is used in conjunction with the :nth-child
family of pseudo-classes to provide fine-grained control over the styling of specific elements.
Here's a basic explanation of how :nth-last-child
works:
- nth-last-child(n)
selects elements that are the nth child from the end of their parent. For example, :nth-last-child(1)
selects the last child, :nth-last-child(2)
selects the second-to-last child, and so on.
This pseudo-class is particularly useful for creating styles for the last few elements in a list or container, regardless of how many elements there are. It's commonly used in scenarios where you want to apply different styles to the last few items in a dynamic list or to create visual effects like highlighting the last item.
Here's an example of how you might use :nth-last-child
in CSS:
/* Select and style the second-to-last child element */
ul li:nth-last-child(2) {
font-weight: bold;
color: #FF5733;
}
In this example, the CSS rule selects the second-to-last
<li>
element within a <ul>
and applies a specific style to it.Overall,
:nth-last-child
is a valuable tool for achieving precise and dynamic styling in CSS.
Syntax
element:nth-last-child (odd | even | <number> | <expression>) { /* ... */ }
Values
- oddAll odd item numbers.
- evenAll even item numbers.
- <number>The serial number of the child relative to its parent. Numbering starts with 1, this will be the first item in the list.
- <expression>It is given in the form an ± b , where a and b are integers, and n is a counter that automatically takes the value 0, 1, 2 ...
By using negative values of a and b, some results can also turn out to be negative or equal to zero. However, elements are affected only by positive values due to the numbering of elements starting at 1.
Example
<table>
<tr>
<td>No</td>
<td>Competition</td>
<td>John</td>
<td>Adam</td>
<td>Robert</td>
<td>Paul</td>
</tr>
<tr>
<td>1</td>
<td>Swimming</td>
<td>1:30</td>
<td>2:05</td>
<td>1:15</td>
<td>1:41</td>
</tr>
<tr>
<td>2</td>
<td>Running</td>
<td>15:30</td>
<td>14:10</td>
<td>15:45</td>
<td>16:00</td>
</tr>
<tr>
<td>3</td>
<td>Shooting</td>
<td>70%</td>
<td>55%</td>
<td>90%</td>
<td>88%</td>
</tr>
</table>
table {
width: 100%;
border-collapse: collapse;
border-spacing: 0;
}
td {
border: 1px solid #333;
padding: 3px;
border-left: 3px double #333;
}
td:nth-last-child(2n+1) {
background: #a3ffa8;
}
td:nth-child(1) {
border: 1px solid #333;
background: #d9a3ff;
}
Browser Support
The following table will show you the current browser support for the CSS :nth-last-child
pseudo class.
Desktop | |||||
12 | 4 | 3.5 | 9 | 3.1 |
Tablets / Mobile | |||||
18 | 4 | 10.1 | 2 | 1 | 37 |
Last updated by CSSPortal on: 1st October 2023