The Lab

An Easy Flexbox Grid System

View Demo | Download Source

#Overview

While coding the post Bulletproof Radio Buttons I needed a simple four column gird to make a set of lists easier to read and improve the page layout. I thought about using a grid framework but it seemed like a lot of work to solve such a simple problem. In the end I wrote my own simple grid system because I wanted the task to be completed quickly and the code to be light. Here’s how I did it.

#Goals

#HTML

Part 1: The HTML is fairly straight forward in this example. We start by wrapping our child divs, cols-4 and cols-2 inside the parent, grid.

<div class = "grid">
    <div class = "cols-4">1/4</div>
    <div class = "cols-4">1/4</div>
    <div class = "cols-4">1/4</div>
    <div class = "cols-4">1/4</div>
</div>
<div class = "grid">
    <div class = "cols-2">1/2</div>
    <div class = "cols-2">1/2</div>
</div>

#Flexbox

Part 2. Now we need to set flexbox up on the parent div, “grid”. To do so I assign it the following properties: display: flex to call flexbox, flex-direction: row to set the child divs as a row of columns and justify-content: space-between to set the gutters equally between the columns.

.grid { 
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
}

#Media Queries

Part 3. Here we will adjust the columns' width to expand to 100% on small screens to keep the line length at a legible and easy to read width.

// Set all columns width to 100% on small screens
.cols-2, .cols-4 {
    flex-basis: 100%;
}

// Set the width of the columns when the window is larger then 800px
@media only screen and (min-width: 800px) {
    .cols-2 {
       flex-basis: 47.5%;
    }

    .cols-4 {
       flex-basis: 21.125%;
    }
}