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

How to Select the Second Last Element in CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 19:26:02337browse

How to Select the Second Last Element in CSS?

Selecting the Second Last Element with CSS

In web development, it's often necessary to target specific elements within a document structure. When choosing the element based on its position within its parent, CSS provides the :last-child selector, which allows us to select the last element. However, in certain scenarios, we may need to select the second last element.

For this purpose, CSS3 introduces the :nth-last-child(n) selector, where n represents the position of the element counting from the end. To select the second last element, we can use :nth-last-child(2).

This selector is applicable to the following example:

<code class="html"><div id="container">
  <div>a</div>
  <div>b</div>
  <div>SELECT THIS</div> <!-- target element -->
  <div>c</div>
</div></code>

Using the :nth-last-child(2) selector, we can style the desired element without the need for jQuery.

Browser Support:

The :nth-last-child selector is supported by modern browsers, including:

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

The above is the detailed content of How to Select the Second 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