Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distribute elements evenly across rows in a flexbox?

Tags:

html

css

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?

like image 239
Lucas Avatar asked Jul 26 '16 10:07

Lucas


People also ask

How do you divide flex into rows?

You can set the col-bordered elements display to flex as well and use flex-flow of column nowrap . Setting flex to 1 on the child elements of col-bordered will force them to have equal height. I have also set the flex property of col-bordered to 0 1 50% to give them an equal width. Here is the example.

How do you show 3 items per row in flexbox?

For 3 items per row, add on the flex items: flex-basis: 33.333333% You can also use the flex 's shorthand like the following: flex: 0 0 33.333333% => which also means flex-basis: 33.333333% .

How do I arrange items in flexbox?

Justify Content Flex Start positions element at the start of the page. Flex End sets the element to the end of the page. Space Around arranges the items evenly but with spaces between them. The spaces will be equal among all the elements inside a flex-box container, but not outside them.


1 Answers

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
like image 169
Paulie_D Avatar answered Oct 29 '22 21:10

Paulie_D