fr Units and Auto-Placement in Grid

What the fr Unit Means

fr stands for a "fraction" of the leftover space in a grid container, after any fixed-size tracks have been subtracted. It lets flexible and fixed columns coexist in the same layout.

.layout {
  display: grid;
  grid-template-columns: 200px 1fr 1fr;
}

Here the first column is a fixed 200px, and the remaining space is split evenly between the second and third columns, since both claim 1fr.

Uneven fr Ratios

.layout {
  grid-template-columns: 1fr 2fr;
}

This splits the remaining space in a 1:2 ratio - the second column ends up twice as wide as the first, and this ratio adjusts automatically as the container is resized.

Auto-Placement of Grid Items

If items are not explicitly assigned a row or column, Grid automatically places them into the next available cell, filling the defined tracks row by row by default.

.gallery {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: 150px; /* size for any rows created automatically */
}

grid-auto-rows controls the size of rows that Grid creates automatically once there are more items than the explicitly defined rows can hold.

Changing the Auto-Placement Direction

.layout {
  grid-auto-flow: column; /* fills columns first instead of rows */
}

Why fr Is Often Preferred Over Percentages

Unlike percentages, fr automatically accounts for gaps and fixed-size tracks in the same row, so column widths stay accurate even when gap or a fixed sidebar width is added later.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.