CSS select all child elements except first two and last two

CssCss Selectors

Css Problem Overview


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;
}

Css Solutions


Solution 1 - Css

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

Check it out here.

Solution 2 - Css

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.

Solution 3 - Css

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRudieView Question on Stackoverflow
Solution 1 - CssspikyjtView Answer on Stackoverflow
Solution 2 - CssMarcinJuraszekView Answer on Stackoverflow
Solution 3 - CssdarthmaimView Answer on Stackoverflow