CSS Relative Units
Relative units are measured against another value, so elements sized with them scale with the font, the parent, or the viewport.
Relative units are the foundation of flexible, accessible layouts. Because they refer to something else rather than a fixed length, a single value can adapt to different screen sizes and user preferences.
The Common Relative Units
rem for Scalable Type
Because <rem> is always relative to the root, it gives consistent, predictable sizing across the whole document and honors the user's browser font-size setting.
Type scale in rem
<!DOCTYPE html>
<html>
<head>
<style>
h1 { font-size: 2.5rem; }
h2 { font-size: 1.75rem; }
p { font-size: 1rem; line-height: 1.6; }
</style>
</head>
<body>
<h1>Page Heading</h1>
<h2>Section Heading</h2>
<p>Body text sized in rem.</p>
</body>
</html>Viewport Units for Fluid Sizing
A full-height hero
<!DOCTYPE html>
<html>
<head>
<style>
.hero {
min-height: 100vh;
padding: 5vw;
}
</style>
</head>
<body>
<div class="hero">
<h1>Welcome</h1>
<p>A full viewport height section.</p>
</div>
</body>
</html>Note: The ch unit is handy for readable line lengths. Setting max-width: 65ch on paragraphs keeps text columns comfortable to read.
- em compounds through nesting, while rem does not
- % depends on which property you use it with, such as parent width or height
- clamp() pairs beautifully with relative units for fluid yet bounded sizes