Prevent Children from Filling CSS Grid Cell
Here's a way to keep the contents of a cell in a CSS grid layout from filling the whole width of the cell.
Columns are easy
Whip out a grid. It'll solve your problems. They're easy to start and powerfully affect your layout.
.container {
display: grid;
grid-template-columns: 1fr 1fr;
}
I've got two equal columns, and I'm ready to rumble.
Children filling the cell
But now when I put something in the grid -- something that's inline-block
and shouldn't be expanding to fill the cell -- like a button
tag, the buttons are way too wide. They're taking up the entire cell width.
button {
display: inline-block;
}
This is weird and undesirable because each of these buttons should only get as wide as they need to be in order to fit their own button text. But they're all equally huge now.
Justify the items
This can all be remedied with a fairly versatile and widely used CSS attribute that I somehow have never used until this use case.
It is: justify-items
. By default when applied to grids, the value is stretch
. That seems to make sense based on what we've observed as the behavior.
Let's switch that up for justify-items: left
, and we get buttons just the size that they need to be and still aligned within their grid column boundaries:
.container {
display: grid;
grid-template-columns: 1fr 1fr;
justify-items: left;
}
Much better! Do you have other methods that you use for solving this problem?