html - 如何清除 flexbox 元素?

标签 html css flexbox

我需要清除 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/

相关文章:

php - 我的联系表单 php 脚本不工作

javascript - 使用自定义音频 slider 以零音量自动播放

javascript - 打开弹出窗口并在关闭弹出窗口时刷新父页面

php - 我的 php 表单不工作,即不向我的页面发送数据

ios - 用于 html 视频标签的手机上出现大播放按钮

html - 与 flexbox 底部对齐,同时有一个 float 到位

html - 将 margin 应用于 flex 元素

jQuery .load();不处理图像

html - 当设置为 "off"时,CSS 3 复选框值为空

html - 使 flex 行充当列以保留时间轴