Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS flex-wrap property: When does wrapping begin?

Tags:

html

css

flexbox

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>
like image 972
user233232 Avatar asked Jan 07 '23 19:01

user233232


1 Answers

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.

    • Border DEMO
    • Padding DEMO
    • Margin DEMO
  • 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:

    • The container shrinks to 799px.
    • Margin is applied.
    • Border or padding is applied, in the content-box box model.
    • (Essentially, as the flex items are fixed-width, as soon as 1px is added to the line, or 1px is removed from the container, wrapping begins.)

This is a general explanation of wrapping in flex containers. There are other factors that can influence the breakpoint, such as flex-shrink.

like image 63
Michael Benjamin Avatar answered Jan 18 '23 03:01

Michael Benjamin