简体   繁体   English

CSS选择除前两个和后两个之外的所有子元素

[英]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. 必须有一个更清晰的方法,不需要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;
}

You don't even need :not() . 你甚至不需要:not() :nth-child(n+3):nth-last-child(n+3) works fine. :nth-child(n+3):nth-last-child(n+3)工作正常。

Check it out here . 在这里查看

I don't see any other option than using :nth-child and :not(:nth-last-child) . 除了使用之外,我没有看到任何其他选项:nth-child: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))

DEMO DEMO

According to :nth-child reference: 根据: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. :nth-child CSS伪类匹配在文档树中具有an+b-1兄弟的元素,对于n的给定正值或零值,并且具有父元素。

In other words, this class matches all children whose index fall in the set { an + b; ∀n ∈ N } 换句话说,这个类匹配索引落在集合{ an + b; ∀n ∈ N } { an + b; ∀n ∈ 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. :nth-last-child工作方式类似,但是从元素集合的末尾开始,所以:nth-last-child(-n+3)仅匹配从集合结尾开始的2个元素。 Because of :not these 2 elements are excluded from selector. 因为:not这两个元素不是从选择器中排除的。

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 这非常容易阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM