我想根据 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/