Flex-wrap is not wrapping when I reduce the window size
You need to use max-width
instead of width
on the container, you have to allow the container to shrink for the items to wrap.
body {
font-family: arial;
}
p {
color: white;
}
.container {
background-color: #666;
max-width: 800px;
height: 200px;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.item {
padding: 10px;
box-sizing: border-box;
}
.item1 {
flex: 1;
background-color: red;
}
.item2 {
flex: 1;
background-color: blue;
}
.item3 {
flex: 1;
background-color: green;
}
<div class="container">
<div class="item item1">
<h1>ITEM1</h1>
<p>flex: 1</p>
</div>
<div class="item item2">
<h1>ITEM2</h1>
<p>flex: 1</p>
</div>
<div class="item item3">
<h1>ITEM3</h1>
<p>flex: 1</p>
</div>
</div>
Here's why the items aren't wrapping:
You have a flex container set to width: 800px
.
The container has three flex items set to flex: 1
, which is shorthand for:
flex-grow: 1
flex-shrink: 1
flex-basis: 0
This means that the actual width of each item is 0
(flex-basis: 0
), and each item is sized based on the available space on the line (flex-grow: 1
).
So, in effect, you've sized each item to be one-third of the space on the line, whatever that may be. Therefore, each item can shrink to width: 0
, and they will never wrap.
If you add content and/or width
and/or flex-basis
to one or more items, and the items grow to exceed 800px (the width of the container), then your flex items will wrap.
But note, they won't wrap based on your re-sizing of the browser window, because the container doesn't occupy width: 100%
of the viewport. They will only wrap based on the width of the container.
body {
font-family: arial;
}
p {
color: white;
}
.container {
background-color: #666;
width: 800px;
height: 200px;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.item {
padding: 10px;
box-sizing: border-box;
}
.item1 {
flex: 1 0 250px;
background-color: red;
}
.item2 {
flex: 1 0 250px;
background-color: blue;
}
.item3 {
flex: 1 0 400px;
background-color: green;
}
<div class="container">
<div class="item item1">
<h1>ITEM1</h1>
<p>flex: 1 0 250px</p>
</div>
<div class="item item2">
<h1>ITEM2</h1>
<p>flex: 1 0 250px</p>
</div>
<div class="item item3">
<h1>ITEM3</h1>
<p>flex: 1 0 400px</p>
</div>
</div>