用css为子元素分配相等的宽度 [英] Allocate equal width to child elements with css
问题描述
我有一个固定宽度的区域,根据具体情况,我需要放置四个div或两个。
如果我有两个div,它应该看起来像这样:
如果我有四个div,它应该是这样的,
目前,我将放置四个div,宽度 25%
。我该如何管理,使用 CSS
来设置条件:如果我只有两个div,请将div大小增加为50%,以将目标区域完全覆盖为四个divs does。
编辑
有时我不想显示橙色区域或 225%
区域。在这些情况下,我需要拉伸黄色区域和 200%
区域。
< div class =wpr >
< div>< / div>
< div>< / div>
< div>< / div>
< / div>
解决方案#1 - Flexbox
.wpr {display:flex; width:400px;}。wpr div {flex:1 1 0;边框:1px纯黄色;背景:粉红色; text-align:center; min-height:40px;}
< div class = WPR > < DIV>< / DIV> < DIV>< / DIV> < div>< / div>< / div>< div class =wpr> < DIV>< / DIV> < div>< / div>< / div>< div class =wpr> < DIV>< / DIV> < DIV>< / DIV> < DIV>< / DIV> < DIV>< / DIV> < DIV>< / DIV> < div>< / div>< / div>
$ b
解决方案2 - 包含 table-layout:fixed
的CSS表格b $ b
.wpr {display:table;表格的布局:固定;宽度:400px;最小高度:40px; } .wpr div {display:table-cell;边框:1px纯黄色;背景:粉红色;}
< div class =wpr > < DIV>< / DIV> < DIV>< / DIV> < div>< / div>< / div>< div class =wpr> < DIV>< / DIV> < div>< / div>< / div>
I have a fixed-width area and, depending on the circumstances, I need to place either four divs or two.
If I have two divs, it should look like this:
If I have four divs, it should look like this,
Currently I'm placing four divs with a width of 25%
. How can I manage, with CSS
, to set the condition: if I have two divs only, increase the div sizes to 50% per each to completely cover the intended area as four divs does.
Edit
Sometimes I don't want to display the orange colored area or 225%
area. In these cases, I need to stretch the yellow colored area and the 200%
area.
Assuming the following sample markup:
<div class="wpr">
<div></div>
<div></div>
<div></div>
</div>
Solution #1 - Flexbox
.wpr {
display: flex;
width: 400px;
}
.wpr div {
flex: 1 1 0;
border: 1px solid yellow;
background: pink;
text-align: center;
min-height: 40px;
}
<div class="wpr">
<div></div>
<div></div>
<div></div>
</div>
<div class="wpr">
<div></div>
<div></div>
</div>
<div class="wpr">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Solution #2 - CSS tables with table-layout:fixed
.wpr {
display:table;
table-layout:fixed;
width: 400px;
min-height: 40px;
}
.wpr div {
display:table-cell;
border: 1px solid yellow;
background: pink;
}
<div class="wpr">
<div></div>
<div></div>
<div></div>
</div>
<div class="wpr">
<div></div>
<div></div>
</div>
这篇关于用css为子元素分配相等的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!