DEV Community

Cover image for CSS Grid: auto is greedy until it's with fr
Nancy
Nancy

Posted on

CSS Grid: auto is greedy until it's with fr

Disclaimer: this article assumes you have some understanding of CSS Grid. If not, the CSS Grid course by Wes Bos (free) and the CSS Grid Guide by CSS-Tricks are both great resources.

TL; DR: when setting a grid template, such as using grid-template-columns, auto is "greedy" for left over space except when it's used with fr units. When auto is used with fr, the auto row(s)/column(s) takes up just enough space to fit its content and any remaining space is given to the row(s)/columns(s) defined with fr units.


Note: All the examples in this post are available on Codepen

What is the fr unit?

The fr unit represents a fraction of the available space in the grid container. For example setting grid-template-columns: 1fr 1fr 1fr; would create three equally sized columns that grow and shrink with the container. Also, fr can be greater than 1, like grid-template-columns: 2fr 1fr; which sets the first column to be twice as wide as the second column

What does auto mean in CSS grid?

The auto keyword means to take up the available space to fit the content. If there's space left over then auto is "greedy"; it will take up space to fit the content plus the maximum left over space it can take (EXAMPLE 1). The exception is if auto is used with fr. If min-width/min-height is set on the grid item then the column would be at the smallest the size set by min-width/min-height (EXAMPLE 2)

Example 1: defining three columns using auto

Example 2: defining three columns using auto; the first column has one item set with a min-width

When auto and 1fr have the same effect

If the grid item's contents takes up the same amount of space then auto and 1fr has the same effect, which is to evenly take up the available space (EXAMPLE 3)

Example 3: when auto and 1fr have the same effect

Using auto and fr together

If auto and fr are used together to define the grid template then auto will take up the space it needs for the content. And the remaining space is divided up to the column(s)/row(s) defined by fr units. The auto defined column(s)/row(s) won't get any more of the leftover space. (EXAMPLE 4)

Example 4: auto is not as greedy when with fr

References

Cover image: by Sharon McCutcheon on Unsplash

Top comments (0)