Simple CSS grid with Flexbox

I’ve been playing with CSS flexbox recently and it’s very interesting. I read the guide on CSS-Tricks and a great tutorial on making a grid system using flexbox. After all of that, I want to use flexbox to create a simple responsive grid for equal 4, 3 or 2 columns. I use the very basic of flex and keep it as minimal as possible.

The main reason I want to use flexbox to create a grid is the traditional grid using float has a bid disadvantage: we must clear float of some items on smaller screens. This is an example I made with Bootstrap, resize the browser to see the problem.

To fix it, Bootstrap has some responsive utilities, but that requires you to add extra div.

So I go with flexbox which is simpler and clearer.

CSS grid with Flexbox

Note that I don’t want to create a 12-columns grid like Bootstrap, because it’s redundant in most cases. Here is what I did:

.grid {
    display: flex;
    flex-wrap: wrap;
    margin: -5% 0 0 -5%;
}
.grid > * {
    padding: 5% 0 0 5%;
    width: 100%;
    box-sizing: border-box;
}

/* Tablets */
@media (min-width: 768px) {
    .grid--2 > *,
    .grid--3 > *,
    .grid--4 > * {
        width: 50%;
    }
}

/* Desktops */
@media (min-width: 1024px) {
    .grid--3 > * {
        width: 33.3333%;
    }
    .grid--4 > * {
        width: 25%;
    }
}

Some notes:

  • I use universal selector * because it’s more flexible and doesn’t require an extra class for columns. Just one single .grid on the wrapper with an optional .grid--2, .grid--3, .grid--4 class for 2, 3, 4 columns correspondingly.
  • The grid has a gutter of 5% width. If you don’t want gutter, simply remove the margin and padding from the code.
  • I use width rather than flex-basis or flex-grow, flex-shrink because in a special case when the flex item has a large image, its width will change unexpectedly. I found width is more reliable.

Example

Check out the example here.

You can also take a look at a real website using this code.

Conclusion

Using flexbox is fun. It helps to solve a lot of layout problems. I’ve just started using it a little recently and really love it. If you have any tip with flexbox, share with me in the comments.

2 thoughts on “Simple CSS grid with Flexbox

  1. Great tip. But I think we need small adjustment on the first demo. Due to the iframe width, it looks like on mobile.
    FYI, if we need a “full-featured” grid using flex, we can refer Bootstrap 4 with flex support.
    Last. I like Jetpack comment! 😉

    1. Didn’t notice the problem with small embeded of Codepen! Thanks for letting me know.

      I think BS’s grid is huge and has a lot of redundant thing. I’m moving out from it, even the version 4. Sometimes, we need just simple thing and flexbox is enough (with tiny code!).

Comments are closed.

Meta Box - Creating expert WordPress custom fields and custom meta boxes in minutes! Check it out →