Px vs em vs rem in CSS: Key Differences and Usage
px is a fixed pixel unit, em is relative to the font size of the parent element, and rem is relative to the root (html) font size. Use px for precise control, em for scalable components inside containers, and rem for consistent sizing across the page.Quick Comparison
Here is a quick overview of the main differences between px, em, and rem units in CSS.
| Unit | What It Means | Relative To | Scaling Behavior | Common Use Case |
|---|---|---|---|---|
| px | Pixels | Absolute screen pixels | Does not scale | Precise fixed sizes |
| em | Font size of parent | Parent element's font size | Scales with parent | Component-relative sizing |
| rem | Font size of root | Root (html) font size | Scales with root only | Consistent sizing site-wide |
Key Differences
px is an absolute unit representing exact pixels on the screen. It does not change based on user settings or parent elements, so it offers precise control but can reduce accessibility if text is too small.
em is a relative unit based on the font size of the parent element. This means if a parent has a font size of 20px, then 1em equals 20px. Nested elements using em can compound sizes, which can be useful for scalable components but requires careful management.
rem stands for "root em" and is always relative to the root <html> element's font size, usually 16px by default. This makes rem great for consistent sizing across a whole page, as it ignores parent sizes and only depends on the root.
Code Comparison
This example sets a paragraph's font size using px units.
p {
font-size: 24px;
border: 1px solid black;
padding: 10px;
width: 200px;
}em Equivalent
Here is the same paragraph sized using em units relative to its parent font size (assumed 16px).
body {
font-size: 16px;
}
p {
font-size: 1.5em; /* 1.5 * 16px = 24px */
border: 1px solid black;
padding: 0.625em; /* 10px */
width: 12.5em; /* 200px */
}When to Use Which
Choose px when you need exact control over element sizes and don't want scaling, such as for images or borders.
Choose em when you want elements to scale relative to their container's font size, useful for modular components that adapt inside different contexts.
Choose rem when you want consistent sizing across the entire page that respects user preferences and root font size changes, ideal for typography and layout spacing.
Key Takeaways
px is fixed and precise but not scalable.em scales relative to the parent element's font size.rem scales relative to the root font size for consistency.rem for global sizing and em for component-relative sizing.em to prevent unexpected size compounding.