CSS可以检测一个元素的子元素的数量吗? [英] Can CSS detect the number of children an element has?

查看:1044
本文介绍了CSS可以检测一个元素的子元素的数量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能回答自己的问题,但我非常好奇。

I'm probably answering my own question, but I'm extremely curious.

我知道CSS可以选择父母的个别子女,

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.

例如

container:children(8) .child {
  //style the children this way if there are 8 children
}

我知道这听起来很奇怪,但是我的经理要求我检查一下,没有找到任何东西,所以我决定转向SO

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.

推荐答案

澄清

由于以前的问题,原来的问题,一些SO公民提出了关注,这个答案可能会误导。请注意,在CSS3中,不能根据子节点数将样式应用于父节点。但是,可以根据兄弟姐妹的数量将样式应用于子节点。

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.

原始答案

令人难以置信的是,现在可以完全在CSS3中。

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%;
}

这种技术的信用来到AndréLuís Lea Verou(精致)。

Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).

这篇关于CSS可以检测一个元素的子元素的数量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆