How to divide space in CSS Grid using the fr unit

If every web-page were displayed on a standard desktop screen, we’d only need a fixed layout to make it look fine.

But with 64.35% of web-pages rendered in mobile phones, or tablets, and the plethora of desktop monitor sizes out there, the need of creating flexible layouts has emerged.

In regard to CSS Grid, a flexible grid can adapt to different screen sizes without breaking.

Without it, columns may become too narrow, content may overflow, and large empty spaces may appear in random places.

Flexible grids help the layout fit the screen instead of forcing the screen to fit the layout.

How can you create flexible grids with the fr unit?

In CSS Grid, the fr unit, short for “fraction,” indicates how to split the available space between rows or columns. Unlike a fixed measurement like 200px, an fr value can adjust in size as the screen dimensions change.

See the following example:

Code example of fr units in grid-template-columns.

In this example the grid-template-columns value of two 1fr in a row, creates two columns with the same width. Each column gets one fraction of the remaining space after the gap is taken into account.

You can also give one column more space than another.

Code example of 2fr combined with 1fr to create unequal grids.

In this example, the first column gets one part, while the second gets two parts. The second column is twice as wide as the first.

Using fixed and flexible columns together

The fr unit can be combined with fixed measurements.

As an example, you can have a sidebar with fixed width, and at the same time, the main content expands to fill the remaining space.

Let’s examine one more example.

Code example with a fixed sidebar and 1fr column.

In this example, the sidebar stays at 240px. The 1fr column (main) takes whatever space remains. If the browser window becomes wider, the main area grows. If it becomes narrower, the main area becomes smaller.

Creating equal columns

You can use the repeat() function to create several equal columns.

See the below example.

The grid now has three columns with the same width. However, on a small screen, three columns may become too narrow.

In cases like this, it is better to use responsive approach by using the minmax() function.

Now each card stays at least 220px wide. When there is less room, the cards move to a new row.


Conclusion

Although my blog doesn’t support comments, feel free to reply via email or X.