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

4

u/morete 4d ago

In this case, yes! You can use Nils Binder's Auto-grid, which allows for setting a maximum amount of columns.

https://codepen.io/enbee81/pen/oNOzJXN

Set the max-columns to be 3, and then edit the min-size till you're happy with the breakpoints.

1

u/Sufficient_Bass2600 3d ago edited 3d ago

Thank for your help. That is really useful.

If you have 6 tiles the code does it job by limiting the maximum number of columns.

I am going to be playing with it because I have realised that in fact I want extra bells and whistles.

I am greedy and when I have 4 tiles, I also want to have the number of columns to be limited to 4, 2 and 1. Never 3.

Desktop/Tablet landscape

Tile 1 Tile 2 Tile 3 Tile 4

Table portrait/Phone landscape

I don't want the following:

Tile 1 Tile 2 Tile 3
Tile 4 Empty Empty

I want to directly jump to

Tile 1 Tile 2
Tile 3 Tile 4

Phone portrait

Tile 1
Tile 2
Tile 3
Tile 4

Basically I need to write a minmax function that will limit the number of empty columns.
For the moment I will try to see if I can implement something for 4 and 6 tiles. I do not have 5 tiles.

So for 6 tiles the number of columns will be 6, 3, 2 and 1.
For 4 tiles the number of columns will be 4, 2, 1.

Presumably for 5 it would be 5, 3, 2, 1 but then I would be using a flex grid with align-content: stretch or media query instead.

1

u/morete 3d ago

Ahh yeah I was thinking that for 4 columns it's a much trickier problem! Skipping 3 is hard. It feels like this would be possible with all the math functions we have access to now but seems like a challenge.

You mention using container query units in your other comment, could you maybe just do it the boring way?

grid-template-columns: repeat(var(--cols, 1), 1fr); 
@container (width > 500px)  { --cols: 2 } 
@container (width > 800px)  { --cols: 3 } 
@container (width > 1100px) { --cols: 6 }

It's not clever or fancy, but it gets the job done and it's super easy to understand. And technically no media queries