Select :first-child or :last-child that doesn't contain some specific class

前端 未结 3 787
一个人的身影
一个人的身影 2021-01-21 22:35

Assume we\'re having a list with 5 items and we want to apply some specific styles to the first or the last child. But the functionality of this list will requi

相关标签:
3条回答
  • 2021-01-21 22:42

    As mentioned, this is not possible with CSS selectors. The reason is twofold:

    • :first-child and :last-child represent the first and last children of their parents, period. They do not represent the first and last child elements matching the rest of the selector. Chaining :not(.hide) simply tells the selector to ignore the element if it has the .hide class; it does not change the meaning of the rest of the selector.

    • There is currently no other pseudo-class available for the first or last (or nth) element matching an arbitrary selector.

    Since you're already using jQuery to apply the .hide class, you can use it to apply another class to the first and last elements matching :not(.hide), then target those additional classes in your CSS.

    0 讨论(0)
  • 2021-01-21 22:45

    Do you mean something like this?

    var notHidden = $('div').not('.hide');
    notHidden.first().css('color', 'red');
    notHidden.last().css('color', 'red');
    
    0 讨论(0)
  • 2021-01-21 22:55

    You can add specific style to first visible child, like this:

    .hide {display: none;}
    div:not(.hide){
      color: red;
    }
    div:not(.hide) ~ div:not(.hide){
        color: black; /*reset everything to normal*/
    }
    

    But there is no way select last visible child with css. For this you need use javascript

    0 讨论(0)
提交回复
热议问题