Sub topic 11
Sizing tracks with minmax()
This chapter assumes you know grid-template-columns, the fr unit, and repeat(). It covers minmax(), which sets a lower and an upper limit for a track's size.
What minmax() does
minmax(min, max) makes a track at least min and at most max. The browser picks a size in that range based on the space available.
.layout {
display: grid;
grid-template-columns: minmax(200px, 300px) 1fr;
gap: 1rem;
}The first column is never narrower than 200px and never wider than 300px. It grows toward 300px when there is room. The second column takes the remaining space.
Values you can use
Both arguments accept lengths, percentages, and these keywords:
| Value | Meaning |
|---|---|
| `auto` | As the minimum, the smallest size the content allows. As the maximum, it grows to fit content. |
| `min-content` | The narrowest the content can get without overflowing, for example the longest word. |
| `max-content` | The width the content takes with no wrapping. |
| `1fr` | A share of leftover space. Allowed only as the maximum. |
Two rules to remember. An fr value is valid only as the maximum, so minmax(1fr, 300px) is invalid. If the maximum is smaller than the minimum, the browser ignores the maximum and uses the minimum.
Rows that grow with content
minmax() also works for rows. This is a common use with the implicit grid:
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: minmax(100px, auto);
gap: 1rem;
}Each row is at least 100px tall. A row grows when an item holds more content, so text is not clipped.
The 1fr gotcha
1fr is shorthand for minmax(auto, 1fr). The auto minimum means a track cannot shrink below its content's minimum size. A long unbroken string or a wide image can make "equal" columns unequal, or push the grid past its container.
Setting the minimum to 0 fixes this:
.equal {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1rem;
}All three columns now stay equal, whatever the content. Wide content may overflow its own cell, so pair this with overflow-wrap: anywhere or overflow: hidden on items when needed.
Common errors
- Using
fras the minimum, such asminmax(1fr, 400px). The whole declaration is invalid and is dropped. - Expecting
1frcolumns to be equal when content differs in minimum width. Useminmax(0, 1fr). - Setting a fixed row height such as
100pxand then seeing text overflow. Useminmax(100px, auto).
Exercise
A three-column grid uses grid-template-columns: repeat(3, 1fr). One item contains a very long URL with no spaces, and that column is wider than the others. What change keeps all three columns equal, and why does it work?
Show answer
Use grid-template-columns: repeat(3, minmax(0, 1fr)). 1fr means minmax(auto, 1fr), so the column cannot shrink below the URL's min-content width. A minimum of 0 removes that floor, so the three columns share the space equally.