Until CSS Grid layout arrives, Flexbox is our best option for layouts.
Here’s a very simple set of SASS mixins to make it easy to build simple grids without needing a huge framework (even though I totally love Foundation). Even though a framework makes a lot of things simple, it’s overkill for 90% of the page layout work that I actually do in my job.
For me, the perfect grid system…
- … is lightweight
- … has columns that are flush to the edge of the container, with a gutter in between, and customizable padding inside
- … allows an arbitrary number of columns in the container, with optionally wrapping elements to new lines
- … makes it easy to resize columns individually
If I can do those things, I can build most layouts that I get from a designer.
The concept is simple, but a bit different than your traditional 12-column grid. In this system, you decide on the fly how many columns to have in your grid:
[row] { @include _fg(6); } // six columns
At this point, each child will use 1/6 of the available width of the container (with gutters in between). Want a particular child to use more – like 2/3 of the available width? Here’s how to do that:
.box { @include _fg_width(2/3); }
This will push subsequent items further out of the way, so they’ll wrap differently.
Edit 1/29/2017
The previous versions of this post featured all the code along with usage. But after a pretty major update to this mixin over the last couple days, I’ve decided it’s not a good idea to keep the code in this post as I’ll have to keep updating it. So instead of supplying all code here, I have it all available for you on Github: https://github.com/aaronjamesyoung/simplest-flexbox-grid along with usage and documentation.
Please feel free to play with it and try it in your projects. Then, let me know what improvements need to be made! I would be particularly interested in documentation improvements too.
The big change that just happened is that we’ve augmented the _fg()
mixin to accept a layout (which means you don’t need _fg_width()
as often). So you can say:
@include _fg(2 1);
This will give you a 2/3 column + 1/3 column in your layout.
It may not be “simplest” anymore, but it’s sure still pretty simple and is better now.
Play with it
Try changing the mixin numbers I set above (number of columns, width of box 1), as well as the gutter and padding variables.
http://codepen.io/aaronjamesyoung/pen/yezKpj