Is there a grid-wrap similar to flex-wrap?
Is there a grid-wrap similar to flex-wrap?
Short answer: No, there isn't a CSS property grid-wrap
similar to flexbox's flex-wrap
to wrap elements on smaller screens when they don't fit in a single row.
Long answer: We can use the grid-template-columns
property with a unique value to make equal-width grid items kinda "wrap". Let's find out how.
The goal is to get something like this without using media queries 👇
If you know the basics of CSS Grid, you would know that the below rule along with display: grid
gives us three equal width columns:
grid-template-columns: 1fr 1fr 1fr;
Using CSS repeat()
function, the same rule is written as:
grid-template-columns: repeat(3, 1fr);
The value 1fr
means one fraction. So the space is divided into 3 fractions equally.
Avoiding a grid blowout
In some cases, if one of the grid items is too long, the above rule gives a problem. It's called a "grid blowout". Read this blog post. So let's replace 1fr
with minmax(0, 1fr)
to achieve the same:
grid-template-columns: repeat(3,
minmax(0, 1fr)
);
Items with a minimum width
Now we have 3 columns irrespective of the size of the items within. But we want to specify a minimum width for the items and then make sure that they "wrap" if there isn't enough space. So, let's change the above rule to:
grid-template-columns: repeat(3, minmax(
12rem
, 1fr));
This gives us 3 equal-width columns with a minimum width of 12rem
each.
However, what we want is not 3
columns. We want that number to be flexible. If 3 items of 12rem
each cannot fit, we want to try and fit 2 items, or 1 and so on.
Introducing the auto-fit
keyword
Replacing the number 3 in the above rule with auto-fit, we can achieve our end goal.
grid-template-columns: repeat(
auto-fit
, minmax(12rem, 1fr));
This will automatically fit as many 12rem
items as possible in one row and wrap the rest of them! Isn't that exactly what we want?
And of course you can replace 12rem
with 16rem
or 9rem
based on the type of items you have and not have to use media queries at all! This single rule just wraps the grid items and gives you a responsive layout.
Check out the final working demo for yourself.
Bonus:
If you work with Tailwind CSS, you can use a plugin I created to achieve this same result. Watch this tutorial to understand how to use it and how it works.
Hope you learnt something new today :) Let me know by hitting a "reply" to this mail.
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.