Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS responsive grid layout: grid-column span breaking minmax

Tags:

css

css-grid

I have a neat responsive grid like this:

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

This makes each grid item at least 200px wide. One of the items (the red one) is twice as wide, like this:

grid-column-end: span 2;

Great so far!

grid works fine on large screens

Now when I resize to a small width, the red item forces the grid to two columns. This gives me a weird small column, even though I specified the min width at 200px. Look:

grid breaks at small screens

I would really like the red item to collapse to a single column, so that the grid won't break.

The problem however is, I don't know the width of the total grid, so I can't use a mediaquery that triggers at a specific viewport size.

Is there a way to either force the red item to one column, or maybe to define the grid columns in another way that will solve this problem?

like image 816
tape2 Avatar asked Apr 10 '26 08:04

tape2


1 Answers

You need to keep the dimensions and a little bit of math in mind while using grid. If you're telling an item to span to 2 columns then that means you always want at least 2 columns in your Grid, it'll not turn into a 1 column grid if the screen gets smaller. Now you have a min-width of 400px for your grid.

For that weird sized column, as you have 2 columns and column 2 takes it's min 200px width and the item after that is left with that weird size.

You can write a media query at that breakpoint to tell your item 1 to stay in column 1 and that should fix it.

@media screen and (max-width:415px){
.item1 {
grid-column: 1;
background:red;
}
}

Check out the Codepen I'm linking here

see on Codepen

like image 136
Gulshan Zaman Avatar answered Apr 23 '26 00:04

Gulshan Zaman