
How To Create a Responsive Grid with Flexbox
Ready to make a simple grid system to use for your web development?
Flexbox makes it super simple to create a responsive grid system, no longer is there any need to mess with floats.
Sure you can use a framework such as Bootstrap for a grid system… but when you just need something simple and light… Flexbox will do the trick. Best of all Flexbox is now supported on all major browsers.
The Demo
See all the code in this Pen Flexbox Grid System.
The CSS
With just two classes .row and .column, we can create a nice evenly spaced grid.
.row { display: flex; } @media screen and (min-width: 800px) { .column { flex: 1; } }
Here’s how the CSS breaks down:
- display: flex – defines the flex container
- flex: 1 – tells a flex item to expand to its max size
This grid has a mobile breakpoint set to 800px. You can easily change that or even add more if necessary.
This example will have one layout for small screens and another for all larger screens.
So for small screens, each element will occupy 100% width and for larger screens all columns will be contained in one row.
The HTML
First, create a row.
<div class="row"> <div class="column"> <!-- 100% width --> </div> </div>
The number of columns you add will be evenly sized and distributed. Two columns would look like this.
<div class="row"> <div class="column"> <!-- 50% width --> </div> <div class="column"> <!-- 50% width --> </div> </div>
And three columns like this.
<div class="row"> <div class="column"> <!-- 33% width --> </div> <div class="column"> <!-- 33% width --> </div> <div class="column"> <!-- 33% width --> </div> </div>
Large Screen View
Small Screen View
This grid will also handle nesting nicely.
<h2>Nesting</h2> <div class="row"> <div class="column"> <div class="row"> <div class="column">Nested</div> <div class="column">Nested</div> </div> </div> <div class="column"> Nothing Nested </div> </div>
More Complex Layouts
But what if you want a layout where the columns are not so evenly spaced. For example, let’s say you want a main content area with two sidebars.
For this example, we will say you want the left sidebar to occupy 20%, the right sidebar to occupy 30% and the main content are to occupy 50%.
<div class="row"> <div class="column _20"> 20% Left Sidebar </div> <div class="column _50"> 50% Main Content </div> <div class="column _30"> 30% Right Sidebar </div> </div>
The extra class names in the column areas can be anything you want, I am keeping it simple and naming then after the percentage width I want.
Here is the only additional CSS you would need.
@media screen and (min-width: 800px) { ._20 { flex: 2.0; } ._50 { flex: 5.0; } ._30 { flex: 3.0; } }
That’s it! Flexbox makes it super simple to create a fully responsive grids.