我需要清除 flex box 布局元素,以便第一个元素的宽度为 100%,第二个元素的宽度为 50%,并以其所在行为中心,第三个和第四个元素的宽度为 50% 在同一行上。
clear 在简单的 block 元素上正常工作,但我找不到使用 flex 布局执行此操作的方法。
https://jsfiddle.net/tzx8qyjt/
.container {
padding: 0;
margin: 0;
list-style: none;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
justify-content: space-around;
}
.item {
background: tomato;
padding: 5px;
width: 100%;
height: 150px;
margin-top: 10px;
margin-bottom: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}
.container.block {
display: block;
}
.container.block .item {
float: left;
box-sizing: border-box;
}
.half {
width: 50%;
}
.container .item.centered {
float: none;
clear: both;
margin-left: auto;
margin-right: auto;
}
<ul class="container">
<li class="item">1</li>
<li class="item half centered">2 Clear after me</li>
<li class="item half">3</li>
<li class="item half">4</li>
</ul>
<br />
<br />
<br />
<br />
<br />
<ul class="container block">
<li class="item">1</li>
<li class="item half centered">2 Clear after me</li>
<li class="item half">3</li>
<li class="item half">4</li>
</ul>
最佳答案
由于清除 float 对 flex 元素的作用不同,您可以这样做,在所有元素上设置 box-sizing: border-box
(使填充包含在集合中宽度)然后对于你的 2:nd,你给它一个小的边距,这将迫使其余的到一个新的行
.container {
padding: 0;
margin: 0;
list-style: none;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
justify-content: space-around;
}
.item {
background: tomato;
padding: 5px;
width: 100%;
height: 150px;
margin-top: 10px;
margin-bottom: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
box-sizing: border-box;
}
.half {
width: 50%;
}
.container .item.centered {
margin: 0 10px;
}
<ul class="container">
<li class="item">1</li>
<li class="item half centered">2 Clear after me</li>
<li class="item half">3</li>
<li class="item half">4</li>
</ul>
关于html - 如何清除 flexbox 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43054565/