简体   繁体   中英

How to distribute elements evenly across rows in a flexbox?

If I have something like the following:

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

Assuming flex-direction: row and that three <div></div> elements fit on one line, is it possible for the browser to display 2 on each line, for two lines, instead of displaying 3 on one line, and then 1 on the next?

Assuming flex-direction: row and that three <div></div> elements fit on one line, is it possible for the browser to display 2 on each line, for two lines, instead of displaying 3 on one line, and then 1 on the next?

Implicit in that statement is that each of the divs is equal to or less than 1/3 width of a complete row.

Thus normally your result would be say....

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

However, from the request you seem to wish to break the line/row after the second element.

As explained by @Oriol here this can only be done by either changing the structure or using clever methods to insert either invisible actual or pseudo -elements to force a linebreak.

For example:

 #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 

you can by using flex-wrap:wrap in parent and flex-basis:50% in child

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

Another method to insert a break, using margin-right on an element and an equivalent margin-left on the following.

Hover the container to see it adapting to a new width.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM