Select :first-child or :last-child that doesn'

2020-04-14 09:15发布

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 require to hide some of its items by applying through jQuery a class (let's call it .hide) which will set a display: none; on the targeted items.

The specific styles I was talking at the beginning should be only applied to the FIRST and the LAST items that are visible, so what I'm trying to achieve is to somehow skip the ones which have the .hide class applied on them and are in the same time the first or the last items.

I already tried to do this by combining some :not(.hide) and :first-child/:last-child pseudos, but it doesn't work. Also, trying to use simbling selectors will work at most for the first child, but there's no way right now to select a previous sibling in css so this solution will not cover the last child problem.

Here's a jsfidle where you can better understand what I'm trying to do:

http://jsfiddle.net/3wgxt1oL/

or

HTML

<div class="hide">Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div class="hide">Item 5</div>

CSS

.hide {display: none;}
div:not(.hide):first-child,
div:not(.hide):last-child {color: red;}

3条回答
爷、活的狠高调
2楼-- · 2020-04-14 09:39

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

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.

查看更多
看我几分像从前
3楼-- · 2020-04-14 09:39

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

查看更多
▲ chillily
4楼-- · 2020-04-14 09:46

Do you mean something like this?

var notHidden = $('div').not('.hide');
notHidden.first().css('color', 'red');
notHidden.last().css('color', 'red');
查看更多
登录 后发表回答