CSS units decide how big something is and what that size depends on. A pixel value stays fixed, a percentage depends on the parent, rem depends on the root font size, and viewport units depend on the screen.
Choosing the right unit is a design decision, not just syntax. Use fixed units when a value must be exact, relative units when a layout should adapt, and character-based units when readability matters.
Absolute units represent a fixed measurement. They do not scale naturally based on the screen or parent element, so they are best used when exact sizing is truly needed.
Relative units scale in relation to another value, such as the root font size, parent font size, viewport size, or container size. These units are much more useful for responsive design.
| Unit | Relative To | Common Use |
|---|---|---|
| em | Current element font size | Component spacing tied to local text |
| rem | Root font size | Consistent spacing and typography |
| % | Parent size | Fluid widths and layout sizing |
| vw | Viewport width | Full-width sections, fluid typography |
| vh | Viewport height | Hero sections, full-screen panels |
| ch | Width of the "0" character | Readable text line lengths |
Most production styles mix units. A layout might use rem for spacing, percent for fluid width, ch for readable article length, and px for a one-pixel border. The goal is not to avoid px completely, but to use each unit for the job it does best.
html {
font-size: 16px;
}
body {
font-size: 1rem;
line-height: 1.6;
}
h1 {
font-size: 2.5rem;
}
.container {
width: 90%;
max-width: 72rem;
}
.hero {
min-height: 100vh;
}
.article {
max-width: 65ch;
}
Be careful with viewport height on mobile browsers because browser toolbars can change the visible viewport. Newer units like svh, lvh, and dvh can help when supported, but min-height and flexible layouts are often more reliable than forcing exact full-screen panels.
.article {
width: min(100% - 2rem, 68ch);
margin-inline: auto;
padding-block: clamp(2rem, 6vw, 5rem);
}
.article p {
font-size: 1rem;
line-height: 1.7;
}
.hero {
min-height: 100svh;
padding: 2rem;
}
.lesson-box:empty::before {
content: "CSS Units px em rem vw vh: add visible content";
}
<code>rem</code> is usually better for accessibility and consistency because it respects the root font size more naturally.
Because it compounds based on the current element's font size. Nested elements can grow faster than expected if you are not careful.
They are useful, but mobile browser UI can affect viewport height, so test <code>vh</code>-based layouts on real devices.
Explore 500+ free tutorials across 20+ languages and frameworks.