css - CSS 可以检测一个元素的子元素数量吗?

标签 css css-selectors

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

我知道 CSS 可以选择父级的单个子级,但是如果父级有一定数量的子级,是否支持为容器的子级设置样式。

例如

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

我知道这听起来很奇怪,但我的经理让我检查一下,我自己没有发现任何东西,所以我决定在结束搜索之前求助于 SO。

最佳答案

澄清:

由于原始问题中的先前措辞,一些 SO 市民担心此答案可能具有误导性。请注意,在 CSS3 中,不能根据子节点的数量将样式应用于父节点。但是,可以根据子节点拥有的兄弟数量将样式应用于子节点。


原答案:

令人难以置信的是,这现在完全可以在 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%;
}

诀窍是在第一个 child 也是倒数第 n 个 child 时选择第一个 child 。这实际上是根据 sibling 的数量进行选择。

这项技术归功于 André Luís(发现)和 Lea Verou(完善)。

您不就是喜欢 CSS3 吗? 😄

CodePen 示例:

来源:

关于css - CSS 可以检测一个元素的子元素数量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36476304/

相关文章:

testing - 没有这样的元素 : Unable to locate element: {"method" :"css selector" ,"selector" :".flexipageTabset>.uiTabBar.uiTabItem.title"}

html - 如何在多个 div 类和 id 中选择 span 元素?

css - Safari 或 IE 不显示 HTML5 视频背景

jquery - 跨浏览器溢出 moz-hidden-unscrollable for ContentEditable

html - 一个 div 中文本之前的图像

html - <dt> 元素内文本的 CSS 选择器(定义列表标记)

css - 不将配置应用于css中一个 block 中的多个类的某个类

javascript - 当使用 jQuery slideDown 显示父元素时,Microsoft Edge 中的子元素不可见

javascript - Bootstrap 模式未在页面加载时显示

css - 防止由于滚动条而重新布局