我使用PHP生成了许多div
,我希望div
s的宽度均匀(即2 = 50%,3 = 33%,4 = 25%,等等)无论制作了多少div
个。
我想用CSS做这件事,有可能吗?
.container {
margin: 10px 0;
width: 100%;
}
.container div {
height: 50px;
}
.container div:nth-child(odd) {
background-color: red;
}
.container div:nth-child(even) {
background-color: blue;
}
.twoColumns,
.threeColumns,
.fourColumns {
height: 50px;
}
.twoColumns div,
.threeColumns div,
.fourColumns div {
float: left;
}
.twoColumns div {
width: 50%;
}
.threeColumns div {
width: 33.333333333%;
}
.fourColumns div {
width: 25%;
}
<div>
<h1>Example markup</h1>
<strong>This would be two columns:</strong>
<div class="container">
<div></div>
<div></div>
</div>
<strong>This would be three columns:</strong>
<div class="container">
<div></div>
<div></div>
<div></div>
</div>
<strong>This would be four columns:</strong>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
<div>
<h1>Desired result (using set widths)</h1>
<strong>This is two columns:</strong>
<div class="container twoColumns">
<div></div>
<div></div>
</div>
<strong>This is three columns:</strong>
<div class="container threeColumns">
<div></div>
<div></div>
<div></div>
</div>
<strong>This is four columns:</strong>
<div class="container fourColumns">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
答案 0 :(得分:7)
Flexbox可用于制作相同宽度的元素:
display: flex;
添加到包含元素以使其所有子节点都使用flexbox模型flex: 1;
添加到子元素以允许它们根据需要进行拉伸/收缩
.container {
display: flex;
height: 100px;
margin: 10px 0;
width: 100%;
}
.container div {
flex: 1;
}
.container div:nth-child(odd) {
background-color: red;
}
.container div:nth-child(even) {
background-color: blue;
}
&#13;
<div class="container">
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
&#13;