https://codepen.io/leon-yum/pen/XYpgzj?editors=1100
I'm trying to make sure that on mobile (400px and below) that my flexbox grid sticks to 2 cols / boxes. However whatever I do, either it snaps to 1 column, or each row stays at 3 cols or 4 cols respectively.
Expected at 400px width:
Results:
HTML
<div class="flex-grid-thirds">
<div class="col">This little piggy went to market.</div>
<div class="col">This little piggy stayed home.</div>
<div class="col">This little piggy had roast beef.</div>
</div>
<div class="flex-grid-four">
<div class="col">This little piggy went to market.</div>
<div class="col">This little piggy stayed home.</div>
<div class="col">This little piggy had roast beef.</div>
<div class="col">This little piggy had roast beef.</div>
</div>
CSS
.flex-grid-thirds,
.flex-grid-four {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
.flex-grid-thirds .col {
width: 32%;
}
.flex-grid-four .col {
width: 24%;
}
@media (max-width: 400px) {
.flex-grid-thirds,
.flex-grid-four {
.col {
width: 40%;
}
}
}
* {
box-sizing: border-box;
}
body {
padding: 20px;
}
.flex-grid {
margin: 0 0 20px 0;
}
.col {
background: salmon;
padding: 20px;
}
Here is the working solution: https://codepen.io/anon/pen/vrgZVa?editors=1100.
All you need, is just to put all items inside one wrapper element (now you have 2 elements), and give flex-wrap: wrap
property to this wrapper. And another one thing to do: give the width to your items (percents are preferrable), and if you will give them width: 50%
, there will be 2 columns, if width: 33%
- 3 columns and so on. I didn't touch margins and such small stuff, just demonstrate what you asked for:
.flex-grid {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
flex-wrap: wrap;
}
.flex-grid-thirds .col {
width: 32%;
}
.flex-grid-four .col {
width: 24%;
}
@media (max-width: 400px) {
.flex-grid {
.col {
width: 50%;
}
}
}
* {
box-sizing: border-box;
}
body {
padding: 20px;
}
.flex-grid {
margin: 0 0 20px 0;
}
.col {
background: salmon;
padding: 20px;
}
<div class="flex-grid">
<div class="col">This little piggy went to market.</div>
<div class="col">This little piggy stayed home.</div>
<div class="col">This little piggy had roast beef.</div>
<div class="col">This little piggy went to market.</div>
<div class="col">This little piggy stayed home.</div>
<div class="col">This little piggy had roast beef.</div>
<div class="col">This little piggy had roast beef.</div>
</div>