开发者

Select second last element with css

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


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


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.

  • :nth-child Browser Support

#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>


This adds a comma after each LI, an ", or" after the second to the last LI, and a period to the last LI using pure CSS with nth-last-child()::after.

To affect just the second to the last LI delete the last CSS entry and set the second CSS entry's (n+3) content to empty ('').

`<style>
    /* Append endings to LIs.
       Append "," to all but the last 2 LIs.
       Append ", or" to the 2nd to the last LI. 
       Append "." to the last LI. */
    article li:nth-last-child(n + 2)::after {
        /* All but the last row. */
        content: ', or';
    }
    article li:nth-last-child(n + 3)::after {
        /* Overwrite all but the last two rows. */
        content: ',';
     }
     article li:nth-last-child(1)::after {
        content: '.';
     }
</style>
<ul>
    <li>Line 1</li>
    <li>Line 2</li>
    <li>Line 3</li>
    <li>Line 4</li>
</ul>`

Yields

  • Line 1,
  • Line 2,
  • Line 3, or
  • Line 4.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜