Sub topic 3
Fluid Spacing and Padding
Assume you know CSS syntax, the box model, common length units, and basic CSS Grid. This chapter uses comparison functions to make layouts adapt without many breakpoints.
Fluid spacing and padding
clamp() keeps a value between a minimum and maximum while allowing it to grow. max() sets a floor. For example, this section gets more vertical space on wide screens, but never becomes too small or too large:
section {
padding-block: clamp(1rem, 4vw, 3rem);
}
button {
padding-inline: max(1rem, 2vw);
}Grids that adapt without media queries
Grid can choose how many columns fit. minmax() gives each column a minimum and maximum size. The min() guard prevents overflow when the container is narrower than one minimum column.
.cards {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
}auto-fit creates as many tracks as fit, then expands the remaining tracks. Each card normally stays at least 16rem wide.
Keeping fluid layouts accessible
A preferred value made only from vw can respond poorly to browser zoom or user font-size settings. Include a rem term so text scales with the root font size.
.title {
font-size: clamp(1rem, 0.5rem + 3vw, 2rem);
}Test at high zoom. Check that text does not overlap, become clipped, or force unwanted horizontal scrolling.
Calculating the preferred value
To scale from 1rem at 20rem viewport width to 2rem at 60rem, calculate:
- Slope:
(2 - 1) / (60 - 20) = 0.025, or2.5vw. - Intercept:
1 - (0.025 × 20) = 0.5rem.
h2 {
font-size: clamp(1rem, 0.5rem + 2.5vw, 2rem);
}Building a reusable fluid scale
Custom properties store formulas once and reuse them:
:root {
--step-0: clamp(1rem, 0.95rem + 0.25vw, 1.25rem);
--space-m: clamp(1rem, 0.75rem + 1.25vw, 2rem);
}
body {
font-size: var(--step-0);
}
.card {
padding: var(--space-m);
}Pitfalls, debugging, and fallbacks
If a formula fails, inspect the computed value in browser developer tools. Confirm that the minimum is smaller than the maximum and that every unit is valid. For older browsers, place a fixed fallback before the comparison function:
.panel {
padding: 2rem;
padding: clamp(1rem, 4vw, 3rem);
}Exercise
Which function should you use when padding must never be smaller than 1rem but may grow with the viewport?
Show answer
Use max(), such as padding-inline: max(1rem, 2vw).