CSS provides multiple units to define sizes, each with unique reference points and use cases. Understanding how em, rem, %, and px differ is essential for creating flexible, responsive layouts that behave consistently across devices and containers. Choose units based on accessibility and layout needs, and test edge cases in nested containers. Choosing units impacts accessibility and layout; test nested containers and root font-size changes.
Explain the difference between em, rem, %, and px units.
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
CSS measurement units define the scale and adaptability of design elements. Absolute units like px are fixed, while relative units like em, rem, and % scale dynamically based on font size or parent dimensions.
Unit | Definition | Reference Context | Common Use |
|---|---|---|---|
px | Pixel — absolute unit representing a device-independent pixel | Screen pixel grid | Precise layouts, borders, or icons |
em | Relative to the font size of the current element | Parent element’s font size | Padding, spacing, or text sizing that scales with parent |
rem | Relative to the font size of the root element (<html>) | Root element (usually 16px) | Consistent typography across app |
% | Relative to the size of the parent container | Parent’s width or height | Fluid layouts, widths, or positioning |
html { font-size: 16px; }
.container { font-size: 1.25rem; /* 20px */ }
.card { font-size: 1em; /* 20px relative to .container */
padding: 2em; /* 40px */
width: 80%; /* 80% of container width */
border: 2px solid #333; /* 2px fixed border */ }
Best Practices
- Use
remfor typography — it ensures consistent scaling across components. - Use
emwhen nested scaling is desired (e.g., buttons inheriting parent font size). - Use
%for flexible containers that resize with viewport or parent. - Use
pxonly when precision is required (borders, shadows, small icons).
Think of em as ‘relative to the element,’ rem as ‘relative to the root,’ % as ‘relative to the parent,’ and px as ‘fixed and absolute.’
Practical scenario
A responsive card layout uses rem for typography, % for container width, and px for hairline borders.
Common pitfalls
- Using
emfor layout and getting compounded scaling. - Forgetting % depends on the parent size.
- Relying only on px and losing accessibility scaling.
Rem is consistent but less local; em is flexible but can compound. Test by changing root font size.