Home > Software design >  When does the browser decide to wrap a flexbox container?
When does the browser decide to wrap a flexbox container?

Time:07-25

In the following code, will the browser decide whether to wrap the #container element into new lines based on whether the initial sizes exceed the width of the cross axis or the main axis?

#container {
  display: flex;
  flex-wrap: wrap;
  width: 500px;
  height: 500px;
}

#container div {
  flex-basis: 200px;
}
<div id="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

CodePudding user response:

For flex items, they will always depend on the main axis space to decide where to break into new line.

The main axis can be horizontal (default) or vertical, depend on flex-direction

Here is an example, items will break into new row when the total width of items in the current row exceeds 600px

#container {
  display: flex;
  flex-wrap: wrap;
  width: 600px;
  height: 500px;
}

#container div {
  flex-basis: 200px;
  background-color: red;
  border: 1px solid black;
  box-sizing: border-box;
  font-size: 50px;
}
<div id="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
</div>

If you change flex-direction to column, now the main axis becomes vertical, and flex-basis now defines the initial height of the items (instead of width).

And if the total height of items in the current column exceeds 600px, items will break into new column

#container {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  width: 500px;
  height: 600px;
}

#container div {
  flex-basis: 200px;
  box-sizing: border-box;
  border: 1px solid black;
  background-color: red;
  font-size: 50px;
}
<div id="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
</div>

  •  Tags:  
  • css
  • Related