Loading...

What should the flex items do when there are too many on one line?

Sometimes our flexbox will have set dimensions, so there won't always be enough space for all of our flex items on one line. In which case, we need to decide whether or not we want flexbox to try to force them in anyway, or if we'd prefer any items that don't fit to jump to the next line. This is determined by the flex-wrap property.

Much like how the flow of a web page works, flex items can be pushed to a new line. These "flex lines" that are created can also be manipulated by other properties, but we'll see more on that in the following pages. If you decide to wrap your flex items, you can also choose whether to have the overflowing items jump to the flex line before or after the original line. Use flex-wrap: wrap for the jump to go after, and flex-wrap: wrap-reverse for the jump to go before. Notice in the examples below how the main axis you set with the flex-direction property will affect the results of the flex-wrap property.

wrap (row) wrap-reverse (row)
Item 1
Item 2
Item 3
Item 4
Item 1
Item 2
Item 3
Item 4

wrap (column) wrap-reverse (column)
Item 1
Item 2
Item 3
Item 4
Item 1
Item 2
Item 3
Item 4

If you turn wrapping off (use flex-wrap:nowrap), your flexbox will do its best to accommodate the situation. Even if your flex items have specific dimensions set, it'll adjust them to try and squeeze them all in on the same line. The only exception to this is use of the property min-width or min-height, which tells the item it must be at least that size. In such a case, it'll keep them all on the same line, but they'll just flow out beyond the edge of the flex container.

<style>
.container {
display:flex;
flex-direction:row;
flex-wrap:nowrap;
width:500px;
}
.flex-item {
background-color:pink;
margin:5px;
padding:5px;
width:200px;
}
.flex-item_v2 {
background-color:pink;
margin:5px;
padding:5px;
min-width:200px;

}
</style>

<div class="container">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
</div>

<div class="container">
<div class="flex-item_v2">Item 1</div>
<div class="flex-item_v2">Item 2</div>
<div class="flex-item_v2">Item 3</div>
</div>

Item 1
Item 2
Item 3

Item 1
Item 2
Item 3