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

我知道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示例:

资料来源:

Css相关问答推荐

如何让CSS过渡应用时宽度增加,而不是减少?

CSS Grid,意想不到的差距

如何在CSS中使用nextJs来指定基色?

text-size-adjust在我的css中曾经在我的手机上的Chrome上工作,停止工作,仍然在我妻子的手机上工作

在NextJS/Reaction应用程序中显示更新问题

如何使用Bootstrap在切换按钮旁边的手风琴标题中添加链接?

可以在 JavaFX CSS 中同时使用 dropshadow 和 insideshadow 吗?

如何让 v-col 变成可滚动的?

使用 CSS 关键帧动画更改内容

CSS Select 器在 rvest 中找到,在 RSelenium 中找不到

如何添加一个类以在开始时触发转换

循环一个 sass/scss 变量以生成 css 变量

CSS网格使sibling 项目拉伸

如何在特定元素之前 Select 每个元素

全部:初始与使用 CSS 重置

CSS - 等高列?

在表格中使用自动换行:断词

如何在 Firefox 和 Opera 中zoom HTML 元素?

Sass 无效的 CSS 错误:预期的表达式

CSS flex,如何在第一行显示一个项目,在下一行显示两个项目