我可能是在回答我自己的问题,但我非常好奇.
我知道CSS可以 Select 父容器的单个子容器,但是如果父容器有一定数量的子容器,是否支持为容器的子容器设置样式.
例如
container:children(8) {
// style the parent this way if there are 8 children
}
我知道这听起来很奇怪,但我的经理让我判断一下,我自己没有发现任何东西,所以我决定在结束搜索之前求助于so.
我可能是在回答我自己的问题,但我非常好奇.
我知道CSS可以 Select 父容器的单个子容器,但是如果父容器有一定数量的子容器,是否支持为容器的子容器设置样式.
例如
container:children(8) {
// style the parent this way if there are 8 children
}
我知道这听起来很奇怪,但我的经理让我判断一下,我自己没有发现任何东西,所以我决定在结束搜索之前求助于so.
Clarification:个
由於原问题先前的措辞,一些市民担心这个答案可能会误导市民.请注意,在CSS3中,样式不能根据子项的数量应用于parent node.然而,样式can基于子 node 具有的siblings的数量被应用于子 node .
Original answer:个
令人难以置信的是,这完全可以在CSS3中实现.
/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
width: 100%;
}
/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
width: 50%;
}
/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
width: 33.3333%;
}
/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
width: 25%;
}
The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.
这项技术的功劳归功于安德烈·路易斯(AndréLuís)(已发现)和利娅·维鲁(Amp;Lea Verou)(精致).
你不是很喜欢css3吗??
CodePen示例:
资料来源: