Rudie
Rudie

Reputation: 53781

CSS select all child elements except first two and last two

I'm very curious (that's all) to see how you would select all children of an element except the first two and last two.

I've a method, but it's nasty and unreadable. There must be a much clearer method that doesn't need 8 pseudo-selectors.

:not(:nth-child(1)):not(:nth-child(2)):not(:nth-last-child(1)):not(:nth-last-child(2)) {
    background: purple;
}

Yeah, that's pretty horrible. It literally selects all elements that are :not the first or second first or last. There must be a method that uses 2 as a semi-variable, instead of piling on pseudo-selectors.

I thought of another one (still messy):

:not(:nth-child(-1n+2)):not(:nth-last-child(-1n+2)) {
    background: purple;
}

Upvotes: 53

Views: 75225

Answers (3)

spikyjt
spikyjt

Reputation: 2240

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

Check it out here.

Upvotes: 91

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

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.

Upvotes: 31

darthmaim
darthmaim

Reputation: 5148

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

Upvotes: 3

Related Questions