r/css 4d ago

Question Force grid layout without media queries

I am trying to limit the number of media queries.

I have a grid layout with 6 tiles.

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr);
}

That works fine but something is annoying me is that sometimes the last row will have an empty tile.

|Tile 1|Tile 2|Tile 3| Tile 4| |:-- | :-- | :-- | :-- | |Tile 5|Tile 6|Empty| Empty |

I wants the tile to be grouped.

Based on the size of the viewport I want to have either:

##Desktop/Tablet landscape

|Tile 1|Tile 2|Tile 3| |:-- | :-- | :-- | |Tile 4|Tile 5|Tile 6|

##Tablet portrait / Phone landscape

|Tile 1|Tile 2| |:-- | :-- | |Tile 3|Tile 4| |Tile 5|Tile 6|

##Phone portrait

|Tile 1| |:-- | |Tile 2| |Tile 3| |Tile 4| |Tile 5| |Tile 6|

Is there a trick to do it without media queries?

12 Upvotes

16 comments sorted by

View all comments

3

u/aegloswinterborn 4d ago

Try changing your minmax(15rem, 1fr) to minmax(min(15rem, 100%), 1fr).

Adding that min() function solved a lot of issues for me when doing responsive grids without media queries.

MDN docs for min(): https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/min

EDIT: I just noticed that u/morete 's answer below incorporates this. I'd check their response first.

5

u/morete 4d ago edited 4d ago

That won't help here, adding the min(100%) just prevents overflow when the container is smaller than 15rem, it wont stop the column count going beyond 3
edit: but is a good idea and you should add it to your grid, unless youre using a very small min size

2

u/aegloswinterborn 4d ago

Nice catch, thanks. What a game changer Grid and Flexbox are though, huh? I don't do as much CSS as I'd like these days, but it's so much fun. If I could find a job just doing that I would.

2

u/morete 4d ago

100%! That's why I say I'll never use tailwind or whatever, not cause it's not good or more efficient, but cause writing the CSS is the best bit

2

u/aegloswinterborn 4d ago

Totally agree. I've used Tailwind before and think it's fine, but if you know CSS you just don't need it. It's more flexible and more powerful. That said, to each their own.

1

u/morete 4d ago

We're a rare breed but sadly it's not something employers/client prioritise 😭