Sub topic 2
Intrinsic CSS Layouts with `min()`, `max()`, and `clamp()`
Assume you know basic CSS syntax, the cascade, the box model, common length units, and CSS Grid. These functions let CSS choose a value from available space, often without media queries.
`clamp()`: a value with a floor and a ceiling
clamp() accepts three values:
clamp(MINIMUM, PREFERRED, MAXIMUM)The result cannot be smaller than the minimum or larger than the maximum. Between those limits, CSS uses the preferred value.
h1 {
font-size: clamp(1.5rem, 1rem + 2vw, 3rem);
}Here, 1.5rem is the floor, 1rem + 2vw is the fluid preferred value, and 3rem is the ceiling.
Mixing units and nesting functions
CSS comparison functions can mix compatible units. The browser resolves the units in the current context.
.box {
width: min(100%, 40rem);
min-width: max(50%, 20rem);
}min() creates an upper bound. max() creates a lower bound. You can nest these functions when each part expresses a separate constraint:
width: min(100% - 2rem, 70rem);Modern CSS allows the subtraction directly inside min(). Use calc() when it makes a complex expression clearer or when older browser support matters.
A container that never overflows
A centered container needs side gutters on narrow screens and a maximum reading width on large screens:
.container {
width: min(100% - 2rem, 70rem);
margin-inline: auto;
}The container is at most 70rem, but it becomes narrower when its parent is narrow. The 2rem subtraction leaves approximately 1rem on each side, preventing horizontal overflow.
Fluid type with `clamp()`
Use clamp() when text should scale smoothly rather than jump at breakpoints:
:root {
--title-size: clamp(1.5rem, 1rem + 2vw, 3rem);
}
h1 {
font-size: var(--title-size);
}Include a rem component in the preferred value. A preferred value using only vw responds to viewport width but can respond poorly to browser font-size preferences and zoom. The rem component keeps the scale tied partly to the root font size.
Exercise
What value does clamp(1rem, 5rem, 3rem) produce?
Show answer
3rem, because the preferred value exceeds the maximum.