CSS select all child elements except first two and last two

You don't even need :not(). :nth-child(n+3):nth-last-child(n+3) works fine.

Check it out here.


I don't see any other option than using :nth-child and :not(:nth-last-child).

My version: hr:nth-child(n+3):not(:nth-last-child(-n+2))

DEMO

According to :nth-child reference:

The :nth-child CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n, and has a parent element.

In other words, this class matches all children whose index fall in the set { an + b; ∀n ∈ N }.

So nth-child(n+3) matches all elements, starting from the third one.

:nth-last-child works similar, but from the end of element collection, so :nth-last-child(-n+3) matches only 2 elements starting from the end of collection. Because of :not these 2 elements are excluded from selector.


You could simply set your purple to all elements, and then remove it from the 3 unwanted ones:

element { background: purple }
element:first-child, element:nth-child(2), element:last-child, element:nth-last-child(2) {
   background: none; /* or whatever you want as background for those */
}

Thats imho much easier to read