Flexbox中的第一个孩子全角


77

如何将flexbox的第一个孩子设置为全角,而其他所有孩子都设置为flex:1(用于分割空间)?

像这样:

在此处输入图片说明

Answers:


108

您可以将的: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>


无可挑剔的解决方案
Carlos_E。

15

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>


3

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

弹性基础的MDN链接

.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>

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.