CSS Secrets: Using min() Function Instead of Media Queries
Modern CSS gives us powerful math functions to simplify layout logic that used to require media queries.
One of these is the min() function.
With min() we can define a property that depends on multiple values, and the browser will automatically use the smallest one.
This helps us write more responsive and maintainable styles.
Suppose you have a layout with dynamic tiles. For example, a two-column grid where the left column takes 60% and the right 40% of the viewport width. Up to a point, everything scales nicely. But once the viewport becomes larger than 1200 pixels, the layout locks into a static centered block of 1200px wide, with only the background expanding beyond it. Inside this grid, imagine a text element with an ellipsis:
.element {
overflow: hidden;
white-space: nowrap;
min-width: 35vw;
}
At first, this works well. The viewport width unit makes the element scale with the layout. But once the layout becomes static at 1200px, the 35vw value continues to grow with the screen, even though the content area does not. The element starts overflowing its container. The traditional fix would be to add a media query, like this:
@media (min-width: 1200px) {
.element {
min-width: 24rem;
}
}
However, this adds maintenance overhead from a development perspective.
Every time the design changes, you need to update or add matching media queries in your CSS.
That means more code to maintain and a higher chance of inconsistencies.
The min() function solves this by handling the logic directly in the property itself:
- min-width: 35vw;
+ min-width: min(35vw, 24rem);
With this single line, the browser dynamically chooses the smaller of the two values. When the viewport is narrow, 35vw will be smaller and the element will scale smoothly. As the screen grows, once 35vw exceeds 24rem, the browser uses the fixed value instead. This makes the element respect both the responsive layout and the static container without an extra media query!