我可能是在回答我自己的问题,但我非常好奇。
我知道CSS可以选择父容器的各个子容器,但是如果父容器有一定数量的子容器,是否支持对子容器进行样式化。
例如
container:children(8) {
// style the parent this way if there are 8 children
}
我知道这听起来很奇怪,但我的经理让我去看看,我自己什么都没有发现,所以我决定在结束搜索之前转向so。
我可能是在回答我自己的问题,但我非常好奇。
我知道CSS可以选择父容器的各个子容器,但是如果父容器有一定数量的子容器,是否支持对子容器进行样式化。
例如
container:children(8) {
// style the parent this way if there are 8 children
}
我知道这听起来很奇怪,但我的经理让我去看看,我自己什么都没有发现,所以我决定在结束搜索之前转向so。
当前回答
现在我们可以使用:has()选择器来标识条目的数量,并将样式应用到容器中
.container { height: 50px; margin: 10px; } .container:not(:has(*)) { /* 0 elements */ background: yellow; } .container:has(> :last-child:nth-child(1)) { /* 1 element */ background: red; } .container:has(> :last-child:nth-child(2)) { /* 2 elements */ background: blue; } .container:has(> :last-child:nth-child(3)) { /* 3 elements */ background: green; } /* For N elements .container:has(> :last-child:nth-child(N)) { background: red; } */ <div class="container"> </div> <div class="container"> <div></div> </div> <div class="container"> <div></div> <div></div> </div> <div class="container"> <div></div> <div></div> <div></div> </div>
其他回答
如果你打算用纯CSS(使用scss),但你在同一个父类中有不同的元素/类,你可以使用这个版本!!
&:first-of-type:nth-last-of-type(1) {
max-width: 100%;
}
@for $i from 2 through 10 {
&:first-of-type:nth-last-of-type(#{$i}),
&:first-of-type:nth-last-of-type(#{$i}) ~ & {
max-width: (100% / #{$i});
}
}
根据Matt的解决方案,我使用了以下Compass/SCSS实现。
@for $i from 1 through 20 {
li:first-child:nth-last-child( #{$i} ),
li:first-child:nth-last-child( #{$i} ) ~ li {
width: calc(100% / #{$i} - 10px);
}
}
这允许您快速扩展项目的数量。
如果你正在寻找一种方法来样式所有元素,如果超过N个存在(例如2个或更多):
李:first-child nth-last-child (n + 2), 李:第一个孩子:nth-last-child(n+2) ~ li background-color:红; 的 <德> < li >第一< / li > < /德> <德> < li >第一< / li > < li >第二< / li > < /德> <德> < li >第一< / li > < li >第二< / li > < li >第三< / li > < /德>
你可以像这样使用:has选择器:
.parent-element:has(:nth-child(8))
它选择子元素号为8的.parent-element类的元素。如果子数字8不存在,规则将不被应用。
不幸的是:has在firefox中默认不支持。您仍然可以使用它,并为firefox支持添加额外的棘手规则。
不,在CSS中没有这样的东西。但是,您可以使用JavaScript来计算子元素的数量并应用样式。