不加class和id使得倒数三个li背景色为红色
You can achieve this using the nth-last-child()
CSS selector. Here's how:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
li:nth-last-child(-n+3) {
background-color: red;
}
Explanation:
:nth-last-child(n)
selects the nth child element, counting from the last child.:nth-last-child(-n+3)
is a more complex formula. Let's break it down:-n
represents a descending sequence (3, 2, 1, 0, -1...).+3
adds 3 to each number in the sequence.- This results in the selector matching elements 3, 2, and 1, counting from the last child. Any negative result from the formula is ignored.
This approach dynamically styles the last three li
elements regardless of the total number of li
elements present. If you add or remove items from the list, the styling will automatically adjust.