CSS 选择除前两个和后两个之外的所有子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15603957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS select all child elements except first two and last two
提问by Rudie
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.
我有一个方法,但它很讨厌而且不可读。必须有一个更清晰的方法,不需要 8 个伪选择器。
: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.
是的,这太可怕了。它从字面上选择所有元素:不是第一个或第二个第一个或最后一个。必须有一种方法可以2
用作半变量,而不是堆积在伪选择器上。
I thought of another one(still messy):
我又想到了一个(还是乱七八糟的):
:not(:nth-child(-1n+2)):not(:nth-last-child(-1n+2)) {
background: purple;
}
回答by spikyjt
回答by MarcinJuraszek
I don't see any other option than using :nth-child
and :not(:nth-last-child)
.
除了使用:nth-child
and之外,我看不到任何其他选项:not(:nth-last-child)
。
My version: hr:nth-child(n+3):not(:nth-last-child(-n+2))
我的版本: hr:nth-child(n+3):not(:nth-last-child(-n+2))
According to :nth-child
reference:
根据:nth-child
参考:
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 }
.
在
:nth-child
CSS伪类匹配的是有一个元素an+b-1
的兄弟姐妹之前在文档树,对于给定的正或n个零值,并具有父元素。换句话说,这个类匹配索引落在集合中的所有孩子
{ an + b; ?n ∈ N }
。
So nth-child(n+3)
matches all elements, starting from the third one.
所以nth-child(n+3)
匹配所有元素,从第三个开始。
: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.
:nth-last-child
工作原理类似,但从元素集合:nth-last-child(-n+3)
的末尾开始,因此只匹配从集合末尾开始的 2 个元素。因为:not
这 2 个元素被排除在选择器之外。
回答by darthmaim
You could simply set your purple to all elements, and then remove it from the 3 unwanted ones:
您可以简单地将紫色设置为所有元素,然后将其从 3 个不需要的元素中删除:
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
恕我直言,这更容易阅读