In the following example I am using percent values in the flex-basis
property. What makes the browser decide when to start breaking the row?
section {
display: flex;
flex-wrap: wrap;
}
div {
border: 1px solid;
padding: 1rem;
flex: 1 0 10%;
}
body {
margin: 100px;
}
* {
box-sizing: border-box;
}
<section>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</section>
First, the browser determines the width of the container.
(For these examples, I'll assume flex-direction: row
, but the same logic applies to column
.)
Let's say the width has a computed value of 800px.
You have 8 flex items with a width of 10%. So each item is 80px.
Notes:
Because you are using a percentage length, these items will not wrap, even with flex-wrap: wrap
. Why? Because 10% is relative to the container width, and as the parent shrinks so does the child. DEMO
If you tell the flex items to grow as much as possible (flex-grow: 1
), they will still not wrap, even with flex-wrap: wrap
, for the same reason as above. DEMO
However, once you introduce border
, padding
or margin
to the equation, these lengths add to the 10%, and the line of flex items will exceed the width of the container. Now the items will wrap.
The reason borders and padding force a wrap is the default box model: box-sizing: content-box
, which calculates borders and padding in addition to width (flex-basis
). However, by changing the box model to border-box
, the width will include borders and padding, and wrapping can be avoided. DEMO
Note that if borders and/or padding are sizable enough, they may still force a wrap even with border-box
. DEMO.
Note that margins will cause wrapping in either box model because they're always outside the width calculation.
(Read more about the CSS box-sizing
property.)
When using absolute lengths, such as pixels, the wrapping calculation is pretty straightforward. In the simplest terms, let's say we have 8 flex items, each with a width of 100px. These items will fit perfectly in the 800px container.
Wrapping will occur the moment:
content-box
box model.This is a general explanation of wrapping in flex containers. There are other factors that can influence the breakpoint, such as flex-shrink
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With