Andrew Folts
Andrew Folts

Reputation: 519

How do you prevent a grid item from overflowing the grid?

I'm using the following to create a grid that scales from three columns to two, then one on mobile:

grid-template-columns: repeat(auto-fill(minmax(400px,1fr));

It works fine, except on mobile devices the min setting causes each item to overflow the grid container (and screen).

Is there any other way I can write the columns to prevent this?

i.e. "Minimum 400px, except if it overflows the parent container"

Upvotes: 5

Views: 8633

Answers (1)

Colin Bernays
Colin Bernays

Reputation: 142

You can replace 400px with min(400px, 100%). That basically does as you ask, sets the minimum value to 400px unless it overflows, then it is 100%.

Though beware browser support for min: https://caniuse.com/?search=min()

Best practice is to put in two declarations:

grid-template-columns: repeat(auto-fill(minmax(400px, 1fr));
grid-template-columns: repeat(auto-fill(minmax(min(400px, 100%), 1fr));

And the browsers that support it will follow the second one.

Upvotes: 2

Related Questions