Fluid Sizing and CSS Functions
Learning Objectives
- Understand absolute and relative CSS units.
- Use viewport-relative and font-relative lengths.
- Build fluid typography and layouts with min(), max() and clamp().
- Understand modern viewport units.
1. Pixels and Percentages
.container {
width: 90%;
max-width: 1100px;
}CSS pixels are absolute CSS length units, although their relationship to physical display pixels depends on device pixel ratio and browser zoom. Percentages are relative to the reference defined by the property and layout context.
2. em and rem
html { font-size: 16px; }
.parent { font-size: 20px; }
.child { font-size: 1.5em; }
.spacing { padding: 2rem; }For font-size, em is relative to the inherited font size. For many other properties, em is based on the element's computed font size. Rem is relative to the root element's font size.
3. Viewport Units
.hero {
min-height: 100vh;
}
.fluid-title {
font-size: 5vw;
}One vw equals one percent of the viewport width. One vh equals one percent of the large viewport height in modern CSS definitions. On mobile, dynamic browser controls can affect which viewport size is appropriate.
4. Modern Viewport Height Units
.small-viewport { min-height: 100svh; }
.large-viewport { min-height: 100lvh; }
.dynamic-viewport { min-height: 100dvh; }svh represents the small viewport height, lvh the large viewport height, and dvh the dynamic viewport height. Choose according to whether the layout should fit the smallest, largest or current dynamic viewport.
5. min() and max()
.container {
width: min(90%, 70rem);
padding: max(16px, 2vw);
}min() returns the smallest of its arguments and max() returns the largest. They can be used to express fluid constraints without writing many breakpoints.
6. clamp()
h1 {
font-size: clamp(2rem, 5vw, 4rem);
}
.section {
padding-inline: clamp(16px, 4vw, 64px);
}Clamp accepts a minimum, preferred value and maximum. The preferred value can scale with viewport size, while the minimum and maximum prevent excessive shrinking or growth.
7. calc()
.content {
width: calc(100% - 32px);
}calc() performs CSS calculations. The operators + and - require appropriate whitespace around them. Compatible dimensions can be combined, such as percentages and lengths.