如何在flexbox中在行之间均匀分布元素



如果我有以下内容:

<div id="flex">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

假设flex-direction: row和三个<div></div>元素适合一行,浏览器是否可以在每行显示2,而不是在一行显示3,然后在下一行显示1?

假设flex-direction: row和三个<div></div>元素放在一行上,浏览器是否可以在每行上显示2,而不是在一行显示3,然后在下一行显示1?

该语句中隐含的是,每个div都等于或小于完整行宽度的1/3。

因此,通常情况下,你的结果是。。。。

#flex {
  display: flex;
  flex-wrap: wrap;
  background: orange;
}
#flex div {
  border: 1px solid white;
  height: 100px;
  width: 33%;
  background: rebeccapurple;
}
<div id="flex">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

但是,在请求中,您似乎希望打断第二个元素之后的行。

正如@Oriol在这里所解释的那样,这只能通过改变结构或使用巧妙的方法插入不可见的实际元素来强制换行来实现。

例如:

#flex {
  display: flex;
  flex-wrap: wrap;
  background: orange;
  justify-content: space-around;
}
#flex div {
  border: 1px solid white;
  height: 100px;
  width: 33%;
  background: rebeccapurple;
}
#flex::before {
  content: "";
  width: 100%;
  order: 1;
}
div:nth-child(n + 3) {
  order: 2;
}
<div id="flex">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  </div

您可以在父中使用flex-wrap:wrap,在子中则使用flex-basis:50%

#flex {
  display: flex;
  flex-wrap: wrap;
  width: 500px /* choose your width here*/
    
}
#flex div {
  flex: 0 50%;
  border: 1px solid red;
  height: 100px;
  box-sizing: border-box
}
<div id="flex">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

插入换行符的另一种方法,在元素上使用右侧边距,在下面的元素上使用等效的左侧边距。

将容器悬停以查看它是否适应新的宽度。

.container {
  width: 500px;
  height: 100px;
  border: solid 1px green;
  display: flex;
  flex-wrap: wrap;
  transition: width 3s;
}
.child {
  width: 150px;
  border: solid 1px red;
}
.child:nth-child(3) {
  margin-right: 150px;
}
.child:nth-child(4) {
  margin-left: -150px;
}
.container:hover {
    width: 700px;  
}
<div class="container">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
</div>

最新更新