Sizing Units
Overview
CSS provides Absolute units and Relative units. Absolute units (like Pixels px) are rigid and ignore the user's accessibility settings. Relative units (em, rem, %) are fluid and adapt. Using rem (Root EM) for typography and spacing is the gold standard for accessibility. If a visually impaired user changes their default browser font size from 16px to 24px, a site built with px will ignore them, while a site built with rem will scale up everything perfectly and proportionately.
Syntax
/* Absolute Unit (Rigid) */
.box {
width: 500px;
font-size: 16px;
}
/* Relative Unit: Percentages (Relative to the parent's width) */
.half {
width: 50%;
}
/* Relative Unit: REM (Relative to the <html> tag's font size) */
/* If browser default is 16px, 2rem = 32px */
h1 {
font-size: 2rem;
margin-bottom: 1.5rem;
}
/* Relative Unit: EM (Relative to THIS element's font size) */
/* Used heavily for scalable buttons and icons */
.btn {
font-size: 1.2rem;
padding: 0.5em 1em; /* Padding scales perfectly with the font! */
}Common Pitfalls
- Using
emfor font sizes on heavily nested elements. Becauseemlooks at its parent's font size, if you nest threedivsthat each havefont-size: 1.2em, the text will exponentially grow huge (1.2 * 1.2 * 1.2). Always useremfor typography to avoid compounding math. - Setting the
<html>font size to10pxjust to makeremmath easier (e.g.,1.5rem = 15px). This brutally overrides the user's browser accessibility preferences. Never touch the root font size; let it default to what the user chose (usually 16px).
Interview Questions
em and rem?rem (Root em) strictly calculates its value based on the root <html> element's font size, providing a consistent global baseline. em calculates its value based on the font size of the specific element it is applied to (or its closest parent), which can lead to compounding scalability.
Real-World Example
Building a perfectly scalable button using em for padding.
/*
If we change the font-size to 2rem, 3rem, or 10px,
the padding will mathematically scale itself to match perfectly!
*/
.scalable-btn {
font-size: 1rem;
padding: 0.75em 1.5em;
border-radius: 0.25em;
}Check Your Knowledge
Test your understanding of Sizing Units with these quick questions.