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;
}
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))
According to :nth-child
reference:
The
:nth-child
CSS pseudo-class matches an element that hasan+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 }
{ 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.