Grid is Perfect for Responsive Layout
Part 2 of the Flexbox or Grid? series.
We’ve already seen that Grid beats Flexbox for Full Page Layout. But what about responsive designs? Are you better off using Flexbox or Grid? Both tools appear equipped to handle varying screen sizes. You might think Flexbox is a better fit, after all - Flex items can
wrap, etc. But Grid layout actually comes with a few new tricks that will save you a lot of time and trouble for responsive layouts.
Minmax for the Win
The first shiny new tool Grid comes with is minmax, which lets us define ranges for the columns and rows in our layout. In this example we’ve got an orange sidebar that we want to be at least
100px wide, but no more than 30% of the width of the container. Here the container is
500px wide, so our sidebar happily takes up 30% of it (
Here’s the same exact code but in a smaller container. Now our minimum value kicks in and makes sure the orange sidebar doesn’t go any smaller than
Minmax ranges like this are awesome and in many cases mean you won’t even need to use media queries.
We can accomplish a similar effect using Flexbox, but it requires a bit more work. We have to use a combination of
max-width to pull it off:
And there’s a key difference here: with Grid we’re sizing the track where the orange item will go. With Flexbox we have to size the orange item itself. The Grid method is more flexible and easier to adapt.
One Style to Rule Them All
If you do end up needing media queries, with Grid layout you’ll generally have less you need to change to make things adapt. Say we want to change this layout to a single column on mobile. With Flexbox we’d need to change each affected item in the layout, overriding its
min-width. We don’t have to
min-width takes precedence.
For just a couple of items this isn’t too bad, but the more complex your layout the more items you’ll have to override, for every media query. It’s doable, but the Grid way is much cleaner.
All we have to do is tell the items to span two columns, and we’re done!
You can even change your entire grid with a single rule if you want, altering the size & number of columns, rows, gaps, etc. CSS Grid is a fantastic choice for responsive layouts.
Build a responsive design using Grid layout. Play around with
minmax ranges, and experiment with how much you can alter the Grid for different media query breakpoints.