Flexbox中的第一个孩子全宽

时间:2017-01-22 09:25:51

标签: css flexbox

如何在flexbox全宽中设置first-child,将其他所有子设置为UIView(对于拆分空间)?

像这样:

enter image description here

3 个答案:

答案 0 :(得分:64)

您可以将:first-child设置为宽度100%,将其余孩子:not(:first-child)设置为flex: 1。要将它们放在多行上,请在容器上使用flex-wrap: wrap

.container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  background: #e2eaf4;
  padding: 10px;
}

.child {
  display: inline-block;
  font-family: "Open Sans", Arial;
  font-size: 20px;
  color: #FFF;
  text-align: center;
  background: #3794fe;
  border-radius: 6px;
  padding: 20px;
  margin: 12px;
}

.child:first-child {
  width: 100%;
}

.child:not(:first-child) {
  flex: 1;
}
<div class="container">
  <div class="child">Child</div>
  <div class="child">Child</div>
  <div class="child">Child</div>
</div>

答案 1 :(得分:11)

为您的第一件商品添加width: 100%;。其他人flex: 1;

.flex {
  display: flex;
  flex-wrap: wrap;
}

.flex-item:not(:first-child) {
  flex: 1;
}

.flex-item:nth-child(1) {
  width: 100%;
}

/* Styles just for demo */
.flex-item {
  background-color: #3794fe;
  margin: 10px;
  color: #fff;
  padding: 20px;
  border-radius: 5px;
}
<div class="flex">
  <div class="flex-item">
    Child
  </div>
  <div class="flex-item">
    Child
  </div>
  <div class="flex-item">
    Child
  </div>
</div>

答案 2 :(得分:0)

另一种利用flex-basis选项(使用这种格式flex: 1 1 100%时的第三个值)的解决方案。

MDN link for flex-basis

.flexContainer {
  display: flex;
  flex-wrap: wrap;
}

.item:first-child {
  flex: 1 1 100%;
  margin-bottom: 20px;
}

.item {
  flex: 1 1 40%;
  height: 50px;
  background-color: red;
  margin: 0 20px;
}
<div class="flexContainer">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>