Select: first-child or: last-child that does not contain a specific class


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:



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


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

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.