CSS Grid Minmax
The minmax() function is a CSS Grid feature that allows you to define a size range for a grid track (column or row). It sets a minimum and a maximum size, allowing the track to be flexible within those bounds.
1. Syntax
grid-template-columns: minmax(min, max);
min: The minimum size of the track. Can be a length (px, rem), percentage,fr, or keyword (min-content,max-content,auto).max: The maximum size of the track. Can be a length, percentage,fr, or keyword.
Note: If max is smaller than min, max is ignored and min is used.
2. Basic Usage
.container {
display: grid;
/* Column 1: At least 100px, but can grow to 50% */
/* Column 2: At least 200px, but can grow to 1fr (rest of space) */
grid-template-columns: minmax(100px, 50%) minmax(200px, 1fr);
}
3. Keywords
min-content: The smallest size the content can be (e.g., the length of the longest word).max-content: The largest size the content can be (e.g., the length of the whole sentence without wrapping).auto: Similar tominmax(min-content, max-content).
.container {
grid-template-columns: minmax(min-content, 300px);
}
4. The Responsive Grid Trick
One of the most powerful uses of minmax() is combining it with repeat() and auto-fit or auto-fill to create responsive grids without media queries.
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
}
How it works:
minmax(250px, 1fr): Each column must be at least 250px wide. If there is extra space, it can grow (1fr).repeat(auto-fit, ...): The browser fits as many 250px columns as possible into the container.- Result: The grid automatically adjusts the number of columns based on the screen width, and the columns stretch to fill any remaining space.
auto-fit vs auto-fill
auto-fill: Fills the row with as many columns as it can. If there's empty space left, it keeps adding empty columns.auto-fit: Fills the row with as many columns as it can. If there's empty space left, it collapses the empty columns and stretches the existing ones to fit (if they have1fr).