CSS Selector for Second Last Element
When using CSS, it's common to select elements based on their position within a parent element. While :last-child is a popular choice for selecting the last element, is there a way to select the element just before the last one?
To achieve this, you can utilize the :nth-last-child selector in CSS3. Here's how it works:
<code class="css">:nth-last-child(2) { /* Styling for the second last child */ }</code>
In this example, the :nth-last-child(2) selector will match the element that is two from the end of its parent element. In the specified HTML, it would select the following element:
<code class="html"><div>SELECT THIS</div></code>
Here's an updated version of the HTML with the appropriate selector applied:
<code class="html"><div id="container"> <div>a</div> <div>b</div> <div class="second-last">SELECT THIS</div> <div>c</div> </div></code>
<code class="css">#container .second-last { /* Styling for the second last child of #container */ background-color: lightblue; }</code>
The supported browsers for :nth-last-child include:
The above is the detailed content of How to Select the Second-to-Last Element in CSS?. For more information, please follow other related articles on the PHP Chinese website!