Home >Web Front-end >CSS Tutorial >How to Select the Second-to-Last Element in CSS?

How to Select the Second-to-Last Element in CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-05 14:52:02325browse

How to Select the Second-to-Last Element in CSS?

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:

  • Chrome 2
  • Firefox 3.5
  • Opera 9.5 , 10
  • Safari 3.1 , 4
  • Internet Explorer 9

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn