html - 是否可以根据父级中 div 的数量调整父级中 div 的大小?

标签 html css multiple-columns

我想根据 div 的数量调整父级 div 的大小?

例如:

假设父级尺寸为 900px

  • 如果父级中只有一个 div,我希望它的大小为 100%

  • 如果父级内部有两个 div,我希望它们的大小相同:50%

  • 如果父级内部有三个 div,我希望它们的大小相同:33,33333%

  • 如果父级中有四个 div,我希望它们的大小相同:25%

  • (...)

div 的最大数量是4,但可以更多。

是否有可能仅在 CSS 中做到这一点?

最佳答案

是的

这是它的 CSS:

/* one item */
div:nth-child(1):nth-last-child(1) {
width: 100%;
}

/* two items */
div:nth-child(1):nth-last-child(2),
div:nth-child(2):nth-last-child(1) {
width: 50%;
}

/* three items */
div:nth-child(1):nth-last-child(3),
div:nth-child(2):nth-last-child(2),
div:nth-child(3):nth-last-child(1) {
width: 33.3333%;
}

/* four items */
div:nth-child(1):nth-last-child(4),
div:nth-child(2):nth-last-child(3),
div:nth-child(3):nth-last-child(2),
div:nth-child(4):nth-last-child(1) {
width: 25%;
}

一个更短的解决方案是:

/* one item */
div:first-child:nth-last-child(1) {
width: 100%;
}

/* two items */
div:first-child:nth-last-child(2),
div:first-child:nth-last-child(2) ~ div {
width: 50%;
}

/* three items */
div:first-child:nth-last-child(3),
div:first-child:nth-last-child(3) ~ div {
width: 33.3333%;
}

/* four items */
div:first-child:nth-last-child(4),
div:first-child:nth-last-child(4) ~ div {
width: 25%;
}

关于html - 是否可以根据父级中 div 的数量调整父级中 div 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24055193/

相关文章:

c++ - 二维 vector C++ 中的多于两列排序

html - 带有 Angular 组件的 Flexbox 布局

html - 禁用在 HTML <SELECT> 控件上触发的事件

javascript - 使用 rowspan 和 colspan 属性修复表头并可滚动

html - 如何在不影响导航栏高度的情况下扩展 Bootstrap 导航栏品牌的背景颜色

html - 如何将溢出的跨度包装在固定的 div 中

css - 媒体查询和 css LESS FRAMEWORK 4

html - 具有两列居中固定宽度容器的 CSS 布局;一列固定宽度,第二列延伸到页尾

JavaScript 使用复杂的 json 文件