Flex - flex-wrap (Single Line or Multi-Line)
About
A flex container can be either single-line or multi-line, depending on the flex-wrap property.
- flex-wrap: nowrap: (Default)A single-line flex container lays out all of its children in a single line, even if that would cause its contents to overflow.
- flex-wrap: wrap or flex-wrap: wrap-reverse A multi-line flex container breaks its flex items across multiple lines, similar to how text is broken onto a new line when it gets too wide to fit on the existing line.
Articles Related
Example multi-line container
This three examples are based on a row of div an shows the effect of the flex-wrap value. They just differs in their flex-wrap and flex-direction value (Ie known as the flex-flow)
They share all:
- the same HTML (a container with a serie of cell)
<div class="flex">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
- The same css:
- for the first div container: a flex contained on width
- for the item children, a box
.flex {
display: flex;
margin:2rem;
background: #9decf9;
}
.item {
width: 80px;
height: 20px;
background-color: SkyBlue;
border: 1px solid #e7e7e7;
text-align: center;
box-sizing: border-box;
}
default: nowrap
The default value is nowrap and does not take the width into account.
- The area taken (ie background) is the same than the area of each children.
- The children are not 80px but 300/4 = 75px width.
- The children does not overflow
- The width of the container is 300px
.flex {
flex-direction: row;
width: 300px;
/* flex-wrap: nowrap; */
}
wrap a row
wrap a row constrained on width
- The children conserve their original size of 80px
- The background is on two rows. (ie 2x20px of the children)
- The container width is 300px
.flex {
flex-direction: row;
flex-wrap: wrap;
width: 300px;
}
wrap a row constrained on viewport
Below we have included the code in a iframe with a size of 300px and the behavior is the same.
When it wraps:
- The children conserve their original size of 80px
- The background is on two rows. (ie 2x20px of the children)
- The container width is 300px
.flex {
flex-direction: row;
flex-wrap: wrap;
}
wrap-reverse a row
.flex {
flex-direction: row;
flex-wrap: wrap-reverse;
width: 300px;
}
wrap-reverse a row-reverse
.flex {
flex-direction: row-reverse;
flex-wrap: wrap-reverse;
width: 300px;
}
wrap a column
Note that a size via the height and width should be given
.flex {
flex-direction: column;
flex-wrap: wrap;
width: 300px;
height: 60px;
}
wrap-reverse a column
.flex {
flex-direction: column;
flex-wrap: wrap-reverse;
width: 300px;
height: 60px;
}
Management
Set
You can set flex-wrap also via the shorthand notation flex-flow property