Select second last element with css

HtmlCssCss Selectors

Html Problem Overview


I already know of :last-child. But is there a way to select the div:

<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div> <!-- THIS -->
 <div>c</div>
</div>

NOTE: without jQuery, only with CSS

Html Solutions


Solution 1 - Html

In CSS3 you have:

:nth-last-child(2)

See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child

nth-last-child Browser Support:

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

Solution 2 - Html

Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.


The :nth-child CSS3 selector is in fact more capable than you ever imagined!

For example, this will select the last 2 elements of #container:

#container :nth-last-child(-n+2) {}

But this is just the beginning of a beautiful friendship.

#container :nth-last-child(-n+2) {
  background-color: cyan;
}

<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondynamicView Question on Stackoverflow
Solution 1 - HtmlFrosty ZView Answer on Stackoverflow
Solution 2 - HtmlkapaView Answer on Stackoverflow