Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 960
Rudie Avatar asked Mar 24 '13 21:03

Rudie


People also ask

How do I select all child elements except one in CSS?

To select all the children of an element except the last child, use :not and :last-child pseudo classes.

How do I apply CSS to all elements except one?

Approach: Use the :not(selector), also known as negation pseudo-class which takes a simple selector as an argument and allows you to style all the elements except the element specified by the selector.

How do you select all children except first?

To select all child elements except the first with JavaScript, we can use jQuery with the not pseudo-selector to select all elements except the first element. and we want to select the last 2 li elements, then we can write: $("li:not(:first-child)").


1 Answers

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

Check it out here.

like image 194
spikyjt Avatar answered Oct 04 '22 20:10

spikyjt