Select second last element with css

后端 未结 2 1890
日久生厌
日久生厌 2020-11-27 02:58

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

a
b
相关标签:
2条回答
  • 2020-11-27 03:09

    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>

    0 讨论(0)
  • 2020-11-27 03:22

    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
    0 讨论(0)
提交回复
热议问题