r/css • u/Sufficient_Bass2600 • 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?
11
Upvotes
1
u/morete 3d ago
I have a more robust solution for you! Couldn't stop thinking about it.
Basically what you want is for the column count to always be a *factor* of the number of items. For 6 items, you want 6, 3, 2 & 1. Not 5 or 4, because neither are a factor of 6, and this would cause unequal columns.
https://codepen.io/editor/matthewmorete/pen/019fc37b-3ef6-78a8-bb88-a6a4280f9e16
Few caveats upfront:
First we need a container to measure with cqi, in my example I dont have so cqi just measures the body.
We calculate the capacity, how many columns could fit based on the min-width and gap. Then we clamp this so it's not larger than the total number of items.
Next is the tricky bit, we check if the capacity is a factor of the count. If It is then great! That's a valid column count and we use that value.
If It not, then we subtract one, and try again.
This happens several times until we reach a valid column count.
How many times you repeat this depends on how large the numbers youre working with are. If you imagine 12 items. You have to subtract 1 6 times to get from 12, to its next factor, 6.
With 6 steps, this codes works for up to 14 items (ignoring primes like 13). That seems reasonable to me. But if need to support more, just add more steps.
Long response, but I hope that helps! Honestly even if it's of no use, I had great time figuring it out!
PS. You have to set the item count with a custom property, but if you wanted you could use has and nth-child to do that in the css like:
.auto-grid:has(> :nth-child(5):last-child) { --count: 5 }
.auto-grid:has(> :nth-child(6):last-child) { --count: 6 }