我有一个div容器(黑色轮廓),其中包含4个长度和高度相等的div。
我希望4个彩色div对齐,它们之间的空间相等(假设每个彩色div约为容器高度的49.5%,每个div的宽度约为容器的25%)。
我尝试用flex做这件事,但我没有得到我想要的东西。
有人可以帮帮我吗?非常感谢你提前。
<div class="container">
<div class="blue"></div>
<div class="red"></div>
<div class="purple"></div>
<div class="green"></div>
</div>
.container { }
.blue { }
.red { }
.purple { }
.green { }
答案 0 :(得分:3)
因为您似乎在一行中有两列,所以我建议您使用三个个灵活动包。
这是如何工作的:
.container (outer flexbox, flex-direction: row)
-------------------------------------------------------------------
| .innerContainer | .innerContainer | .innerContainer |
-------------------------------------------------------------------
.innerContainer (inner flexbox, flex-direction: column)
--------------- --------------- --------------
| (empty) | | .blue | | .red |
--------------- | .purple | | .green |
--------------- --------------
此外,所有flex-box
个孩子都设置为flex-grow: 1
,因此它们都是相同的尺寸,它们会填满整个空间。
.container {
display: flex;
flex-direction: row;
background-color: #e9e9e9;
height: 100px;
}
.innerContainer {
display: flex;
flex-direction: column;
}
.blue, .red, .purple, .green, .innerContainer {
flex-grow: 1;
margin: 2px 1px;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}
.purple {
background-color: purple;
}
.green {
background-color: green;
}
&#13;
<div class="container">
<div class="innerContainer"></div>
<div class="innerContainer">
<div class="blue"></div>
<div class="purple"></div>
</div>
<div class="innerContainer">
<div class="red"></div>
<div class="green"></div>
</div>
</div>
&#13;
答案 1 :(得分:1)
* { box-sizing: border-box; }
.container {
display: flex; /* create flex container */
flex-direction: column; /* align children vertically */
flex-wrap: wrap; /* allow multiple columns */
align-content: flex-end; /* shift columns to container end */
height: 100px;
width: 400px;
border: 2px solid black;
}
.container > div {
margin: 5px; /* equal spacing between divs */
width: calc(25% - 10px); /* width less margin */
height: calc(50% - 10px); /* height less margin */
}
.blue { background-color: blue; }
.purple { background-color: purple; }
.red { background-color: red; }
.green { background-color: green; }
&#13;
<div class="container">
<div class="blue"></div>
<div class="purple"></div>
<div class="red"></div>
<div class="green"></div>
</div>
&#13;