▦ CSS Grid Generator
Set the number of columns, rows and gap size to build a display: grid CSS snippet, with a live preview.
What 1fr resolves to
Three numbers produce a container rule that splits the space into equal tracks:
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 1fr);
gap: 12px;
track size = (container size - (count - 1) × gap) / count
The gaps are subtracted first, then whatever is left is shared out. In a 600px
wide container with 3 columns and a 12px gap, the two gaps take 24px and each
column settles at 576 / 3 = 192px. Add a fourth column and the same 600px gives
three gaps of 12px and columns of 141px. The fr unit is a share of
the remaining free space, which is why it never overflows the way a
33.33% column plus a gap does.
Where to take it next
- Rows rarely want a fixed count. Drop the
grid-template-rowsline and rows are created implicitly as items arrive; addgrid-auto-rows: minmax(120px, auto)to give them a floor. - For a responsive grid, swap the column line for
repeat(auto-fit, minmax(240px, 1fr)). The column count then follows the container width with no media query. - Mixed track sizes are fine.
grid-template-columns: 240px 1frpins a sidebar and lets the main column take the rest.
1fr is shorthand for
minmax(auto, 1fr), so a track will refuse to shrink below its
content. One long URL or unbroken word in a cell will push the whole grid wider
than its parent. Use minmax(0, 1fr) when the content must be allowed
to overflow instead.Frequently asked questions
What does 1fr mean in CSS grid?
One fraction of the free space left after fixed tracks and gaps are taken out. repeat(3, 1fr) gives three tracks of equal width; 2fr 1fr gives the first track twice the width of the second.
Why is my grid wider than its container?
A cell has content that cannot shrink, and 1fr will not go below it. Replace the track with minmax(0, 1fr), or put overflow-wrap: anywhere on the cell.
Should I use grid or flexbox?
Grid when you are placing things in both directions at once and want rows and columns to line up across the whole container. Flexbox when it is a single row or column of items that should size themselves to their content.