How to Use min() and max() Functions in CSS
In CSS,
min() and max() functions let you set size values that adapt by choosing the minimum or maximum from a list of values. Use min() to limit a size to the smallest value and max() to ensure a size is at least the largest value specified.Syntax
The min() and max() functions take one or more comma-separated values and return the smallest or largest value respectively.
min(value1, value2, ...): Returns the smallest value.max(value1, value2, ...): Returns the largest value.
Values can be lengths (like px, rem), percentages, or calculations.
css
width: min(300px, 50%); height: max(100px, 20vh);
Example
This example shows a box that is never wider than 300 pixels but can shrink to 50% of its container, and a height that is at least 100 pixels but can grow up to 20% of the viewport height.
css
html, body {
margin: 0;
height: 100%;
}
.container {
width: 80%;
margin: 20px auto;
border: 2px solid #4a90e2;
padding: 10px;
}
.box {
width: min(300px, 50%);
height: max(100px, 20vh);
background-color: #a0c4ff;
display: flex;
align-items: center;
justify-content: center;
font-family: Arial, sans-serif;
font-size: 1.2rem;
color: #03396c;
border-radius: 8px;
}Output
A blue box centered on the page with width no more than 300px but shrinking to 50% of container, height at least 100px but growing up to 20% of viewport height, with text inside.
Common Pitfalls
Common mistakes when using min() and max() include:
- Using incompatible units without
calc()(e.g., mixingpxandemwithout calculation). - Expecting
min()ormax()to clamp values outside their range; they only pick the smallest or largest value from the list. - Not testing responsiveness, which can cause unexpected sizes on different screens.
css
/* Wrong: mixing units without calc() */ width: min(300px, 50em); /* May cause unexpected results */ /* Right: use calc() to unify units */ width: min(300px, calc(50em));
Quick Reference
| Function | Purpose | Example | Result Explanation |
|---|---|---|---|
| min() | Returns smallest value | width: min(200px, 50%) | Width will be the smaller of 200px or 50% of container |
| max() | Returns largest value | height: max(100px, 10vh) | Height will be at least 100px or 10vh, whichever is larger |
Key Takeaways
Use
min() to limit a size to the smallest value among options.Use
max() to ensure a size is at least the largest value specified.Combine different units carefully, using
calc() if needed.Test on different screen sizes to see how min and max affect layout.
These functions help create flexible, responsive designs without media queries.