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 thanflex-basis
orflex-grow
,flex-shrink
because in a special case when the flex item has a large image, its width will change unexpectedly. I foundwidth
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.
Leave a Reply