CSS Units Explained: PX vs. REM vs. EM
CSS projects often mix px, rem, and em values. Knowing what each unit is relative to makes it easier to maintain consistent typography, spacing, and component sizing. The important distinction is not just the number; it is the reference size used by the unit.
PX: a fixed CSS length value
The px unit is a CSS length unit that does not scale from the document's root font-size. It is often used when a design calls for a specific CSS dimension, such as a thin border or an exact icon size.
A CSS pixel is not necessarily the same thing as one physical screen pixel. Browsers map CSS pixels to device pixels according to the display and page scale.
REM: relative to the root font size
One rem equals the computed font size of the root element, usually the html element. If the root font size is 16px, then 1rem corresponds to 16px and 1.5rem corresponds to 24px.
Because rem values share the same root reference, they are useful when a project wants typography and spacing to follow a consistent scale.
With a 16px root font size
16px = 1rem
24px = 1.5rem
32px = 2remEM: relative to an element's font-size context
An em value is relative to the relevant element's font-size. In many common cases, a child element inherits a font size from its parent, so em-based sizing can change as the component's font-size context changes.
This makes em useful for component styles that should scale with their own typography. It also means you must identify the correct element context before converting an em value to pixels.
The same 2em value with different reference sizes
At 16px: 2em = 32px
At 20px: 2em = 40pxConversion formulas
For a selected reference font size, the converter uses the following arithmetic. The reference must match the root font size for rem conversions and the relevant element context for em conversions.
| Conversion | Formula | Example with a 16px reference |
|---|---|---|
| PX to REM | PX ÷ reference size | 24px ÷ 16 = 1.5rem |
| REM to PX | REM × reference size | 1.5 × 16 = 24px |
| PX to EM | PX ÷ reference size | 24px ÷ 16 = 1.5em |
| EM to PX | EM × reference size | 1.5 × 16 = 24px |
Choose the right reference before converting
- For rem, use the root element's computed font size.
- For em, use the font size relevant to the element and property being checked.
- Do not assume that every component uses the same em reference.
- Use px when you need a specific CSS length that should not be calculated from a font-size reference.
