Flexbox columns

Back to list

This is a Bootstrap-but-headache-free way to get inline columns of whatever width you want with flexbox. This sort of thing is also doable with grid, but it's much more troublesome because you have to define the number of columns in advance (which can get real annoying when you want to change the layout). Not the case here!

I styled the demo so you can actually see how big the boxes are, but the code itself comes completely unstyled. You'll probably want to add some margins and padding to make everything less cramped. If you're having issues with overflow, it's likely due to padding inflating the widths - you can fix this by replacing, say, "50%" with calc(50% - npx), where n is twice the amount of padding you have. (Twice because padding is applied to both sides!)

On mobile or smaller screens, the flex designation is removed from the container so all the boxes display vertically instead.

Demo

This is a half-width box
This is a half-width box
This is a third-width box
This is a two thirds-width box
This is a three quarter-width box
This is a quarter-width box

Code

CSS:

.flexcontainer {
    display:flex;
    flex-wrap:wrap;
    margin:auto;
}

.full { flex: 1 1 100%;}
.half { flex: 1 1 50%; }
.third { flex: 1 1 33%; }
.twothird { flex: 1 1 66%; }
.quarter { flex: 1 1 25%; }
.threequarter { flex: 1 1 75%; }

@media screen and (max-width: 1024px) {
    .flexcontainer {
        display:block;
    }
}

HTML:

<div class="flexcontainer">
<div class="half">This is a half-width box</div>
<div class="half">This is a half-width box</div>
<div class="third">This is a third-width box</div>
<div class="twothird">This is a two thirds-width box</div>
<div class="twothird">This is a three quarter-width box</div>
<div class="quarter">This is a quarter-width box</div>
</div>