How to Use minmax() in CSS Grid for Flexible Layouts
Use the
minmax(min, max) function in CSS Grid to set a grid track's size with a minimum and maximum value. It allows grid columns or rows to grow and shrink between these limits, making layouts flexible and responsive.Syntax
The minmax() function takes two values: min and max. These define the minimum and maximum size a grid track (column or row) can have.
min: The smallest size the track can shrink to.max: The largest size the track can grow to.
You use it inside grid-template-columns or grid-template-rows like this:
css
grid-template-columns: minmax(min, max);
Example
This example creates a grid with three columns. The first and third columns have fixed widths, while the middle column uses minmax(100px, 1fr). This means the middle column will be at least 100 pixels wide but can grow to fill available space.
css
html, body {
height: 100%;
margin: 0;
}
.container {
display: grid;
grid-template-columns: 150px minmax(100px, 1fr) 150px;
gap: 10px;
height: 100vh;
padding: 10px;
background-color: #f0f0f0;
}
.box {
background-color: #4a90e2;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.2rem;
border-radius: 5px;
}
Output
<div class="container"><div class="box">150px</div><div class="box">minmax(100px, 1fr)</div><div class="box">150px</div></div>
Common Pitfalls
One common mistake is setting the min value larger than the max value, which will cause the browser to ignore the rule or behave unexpectedly.
Also, using fixed units for max can limit flexibility. Using flexible units like fr helps the grid adapt better.
css
/* Wrong: min is larger than max */ grid-template-columns: minmax(200px, 100px); /* Right: min is smaller than max */ grid-template-columns: minmax(100px, 200px);
Quick Reference
| Property | Description | Example |
|---|---|---|
| minmax(min, max) | Sets min and max size for a grid track | minmax(100px, 1fr) |
| min | Minimum size the track can shrink to | 100px, auto, 10rem |
| max | Maximum size the track can grow to | 1fr, 300px, auto |
Key Takeaways
Use minmax(min, max) to create flexible grid tracks with set minimum and maximum sizes.
The min value must be less than or equal to the max value to work correctly.
Combine minmax with flexible units like fr for responsive layouts.
minmax can be used in grid-template-columns and grid-template-rows.
Avoid fixed max sizes if you want the grid to adapt fluidly to screen size.