CSS能检测一个元素的子元素数吗? [英] Can CSS detect the number of children an element has?
问题描述
我可能回答自己的问题,但我非常好奇。
我知道CSS可以选择父母的个别子女,但有支持
例如
container:children(8).child {
//如果有8个孩子,则以这种方式设置子样式
}
我知道这听起来很奇怪,但是我的经理让我看看,没有找到任何东西,所以我决定转向SO
b b b b b b
由于先前的问题,原来的问题,一些SO公民提出了关注,这个答案可能会误导。请注意,在CSS3中,不能根据子节点数将样式应用于父节点。但是,可以根据他们拥有的兄弟姐妹数将样式应用于子节点。
原始答案:
令人难以置信的是,现在可以完全在CSS3中。
/ *一个项目* /
li:first-child:nth-last-child(1){
width:100 %;
}
/ *两个项目* /
li:first-child:nth-last-child(2),
li:first-child:nth- last-child(2)〜li {
width:50%;
}
/ *三项* /
li:first-child:nth-last-child(3),
li:first-child:nth- last-child(3)〜li {
width:33.3333%;
}
/ *四项* /
li:first-child:nth-last-child(4),
li:first-child:nth- last-child(4)〜li {
width:25%;
}
此信息适用于AndréLuís Lea Verou(精致)。
不要只是喜欢CSS3吗?
I'm probably answering my own question, but I'm extremely curious.
I know that CSS can select individual children of a parent, but is there support to style the children of a container, if its parent has a certain amount of children.
for example
container:children(8) .child {
//style the children this way if there are 8 children
}
I know it sounds weird, but my manager asked me to check it out, haven't found anything on my own so I decided to turn to SO before ending the search.
Clarification:
Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.
Original answer:
Incredibly, this is now possible purely in CSS3.
/* one item */
li:first-child:nth-last-child(1) {
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%;
}
Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).
Don't you just love CSS3?
这篇关于CSS能检测一个元素的子元素数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!