PX to EM: sizes relative to the surrounding text
This px to em converter divides pixel values by a base font size to produce em units. Unlike rem, an em is relative to the font size around it, so the base you enter should be the font size of the context your CSS rule applies in, not automatically 16px.
What an em refers to
- For the
font-sizeproperty, 1em equals the parent element's font size. - For other properties such as
padding,margin,gaporborder-radius, 1em equals the element's own computed font size.
That second rule is what makes em useful: a button with padding: 0.75em 1.5em keeps its proportions whether the button text is 14px or 20px.
Examples
16px base: 18px = 1.125em 40px = 2.5em
20px base: 12px = 0.6em 18px = 0.9em
14px base: 3px = 0.2143em
If a card title should be 18px and the card's text is 16px, its font size is 1.125em. If a caption inside a 20px block should be 12px, it is 0.6em.
Compounding: the em trap
Because font-size ems multiply through nesting, the same rule can produce different sizes at different depths. Suppose nested lists all use font-size: 0.875em on a 16px page:
level 1: 16 × 0.875 = 14px
level 2: 14 × 0.875 = 12.25px
level 3: 12.25 × 0.875 = 10.71875px
Three levels deep, the text has shrunk by a third. When you do not want that effect, use rem for font sizes and keep em for spacing inside components. The PX to REM converter handles that case.
em in media queries
Media queries written in em (such as @media (min-width: 48em)) do not use your root or parent font size. They use the browser's initial font size, normally 16px, so 768px is 48em for breakpoints no matter what the page's root rule says.
To go back from em to pixels for a specific depth, use the EM to PX converter, and format the finished rules with the CSS formatter.
Worked example: converting a button
Take a button designed with 18px text, 12px × 24px padding and a 6px radius, placed in a paragraph whose text is 16px. The two em rules mean you need two different bases:
font-size: 18 ÷ 16 = 1.125em (parent is 16px)
padding: 12 ÷ 18 = 0.6667em
24 ÷ 18 = 1.3333em (element is 18px)
border-radius: 6 ÷ 18 = 0.3333em
Run the conversion twice: once with base 16 for the font size, then with base 18 for everything else. The result is a button that grows and shrinks as a unit. Put it in a sidebar with 14px text and it becomes 15.75px with proportionally smaller padding and corners, with no extra CSS.