Units
Measure sizes with px, em, rem, %, and viewport units.
Syntax
width: 50%; font-size: 1.5rem; height: 100vh;CSS lengths can be absolute or relative.
Common units
px— fixed pixels, absolute.%— relative to the parent element.em— relative to the element's font size.rem— relative to the root font size.vw/vh— relative to the viewport width / height.
Relative units help build layouts that scale with the screen and the user's font settings.
Example
Loading editor…
Press Run to see the result.
When to use it
- A developer sets body font-size in rem so the entire site scales when a user changes their browser's default font size for accessibility.
- A designer uses vw and vh to make a full-screen hero section that fills exactly the browser viewport on any device.
- A layout engineer uses percentage widths on columns so they always total 100% of the container regardless of screen size.
More examples
Absolute px versus relative rem
Shows the practical difference between px (absolute) and rem (scales with the user's browser font preference).
/* Fixed — ignores user browser font preference */
.badge { font-size: 12px; }
/* Scales with root font-size preference */
.label { font-size: 0.75rem; }Percentage and em in containers
Combines % for fluid width with em padding that scales proportionally with the element's own font size.
.container {
width: 90%; /* 90% of the parent */
max-width: 1200px;
padding: 1em; /* relative to this element's font-size */
}Viewport units for full-screen hero
Uses vw and vh to create a section that always fills the full visible browser window on any device resolution.
.hero {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: #eef3ff;
}
Discussion