| px | rem / em |
|---|
px vs. rem vs. em ExplainedChoosing the right CSS length unit is critical for responsive typography and web accessibility. While pixels (px) are fixed physical-reference units, relative units (rem and em) scale automatically based on font size, ensuring your layout respects a user's browser zoom and default font-size preferences.
px (Pixels): Absolute unit in CSS (1px = 1/96th of an inch). Great for 1px hairline borders or fixed shadows, but using px for font sizes overrides the user's browser accessibility settings.rem (Root em): Always relative to the root <html> element's font-size (which defaults to 16px in almost all browsers). Because rem never compounds inside nested elements, it is the preferred unit for typography, spacing, and layout grids.em: Relative to the current element's own font-size (or its parent's for font-size itself). Ideal for button padding or icons that should scale proportionally with the button's text size, though nesting em font sizes can cause unexpected compounding.The conversion formula is straightforward: rem = px / rootFontSize and px = rem × rootFontSize. With the standard 16px root size, 12px = 0.75rem, 14px = 0.875rem, 16px = 1rem, 20px = 1.25rem, 24px = 1.5rem, and 32px = 2rem. The reference table above updates automatically whenever you change the root font size.
html { font-size: 62.5%; }? Setting root font-size to 62.5% makes 1rem = 10px (62.5% of 16px) for easier mental math, while still respecting user browser scaling. However, if you use a component library like Bootstrap or Tailwind, keep the default 16px root so third-party components do not shrink.px or rem? Using rem or em in @media (min-width: 48rem) ensures breakpoints adapt cleanly when users increase their default browser font size.In design systems such as Tailwind CSS and Bootstrap 5, spacing scales are built on 0.25rem (4px) increments: 0.25rem = 4px, 0.5rem = 8px, 0.75rem = 12px, 1rem = 16px, 1.5rem = 24px, 2rem = 32px, and 3rem = 48px. Using rem for font sizes, margins, and container widths while reserving em for button padding and icon alignment keeps components modular and accessible across every screen density.