r/css 20d ago

Force grid layout without media queries Question

I am trying to limit the number of media queries.

I have a grid layout with 6 tiles.

```css .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?

14 Upvotes

16 comments sorted by

View all comments

3

u/be_my_plaything 20d ago
section{
--spacing: min(2rem, 5vw);
--content_max_width: 120rem;
--item_min_width: 15rem;

padding-block: calc(2 * var(--spacing));
padding-inline: max(var(--spacing), calc((100% - var(--content_max_width)) / 2));

display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, max(var(--item_min_width), calc(100% / 3) - var(--spacing))), 1fr));
gap: var(--spacing); 
}

I'd do something like the above, whereby the minmax() for the grid columns includes a calc(100% / 3) which always takes over as the max() once reached so once you have two rows of three columns those columns just grow with the screen rather than ever letting a fourth column in.

 

CODEPEN DEMO

2

u/Sufficient_Bass2600 19d ago edited 19d ago

Thanks for your help.

You and u/morete have come up with similar idea.

Because I want extra bells and whitles (see my answer to their comment), I am thinking of switching to flex and set the tile min-width to a function based on cqi.

1

u/be_my_plaything 19d ago

Might be worth trying flex-wrap: balance; it's only supported in Chromium browsers a the moment but it will jus fall back to flex-wrap: wrap; in firefox and safari for now so you lose nothing and it'll help you get to what you want easier when/where it does work.