Absolute vs Relative CSS Units (px, em, rem, %)
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
Absolute Units: px
A pixel (px) is a fixed unit - 16px is always 16px, regardless of any parent element or user setting. It is predictable, but it does not automatically scale if a user increases their browser's default font size for accessibility.
Relative Units: em, rem and %
| Unit | Relative to |
|---|---|
em | The font size of the current element (or its parent, for non-font properties) |
rem | The font size of the root <html> element - stays consistent no matter how deeply nested |
% | Usually the parent's corresponding size (width, height, font-size, etc.) |
Why em Can Compound Unexpectedly
.parent { font-size: 20px; }
.child { font-size: 1.5em; } /* 30px */
.grandchild { font-size: 1.5em; } /* 45px, relative to .child's 30px */Because em multiplies against its parent's font size, nesting several elements that each use em can cause sizes to grow or shrink faster than expected. rem avoids this by always referring back to the root font size instead of a parent.
Choosing Between Them
- Use
remfor font sizes and spacing - predictable and easy to scale globally by changing the root font size. - Use
%for widths inside a fluid layout. - Use
pxfor things that genuinely should never scale, like a 1px border. - Use
emsparingly, mainly when a value should scale with its own element's font size, such as padding inside a button that should grow with its text.