Kanbritech Learn logo
HTML HTML References 45h track

PX to EM Converter

Convert a 20px font size with a 16px parent, and explain what changes if the parent becomes 20px.

Understand the topic

Pixels are a CSS length unit. An em used for font-size is relative to the inherited font size; an em used for many other properties is relative to the element font size. rem is relative to the root font size. To convert a target pixel font size to em, divide by the relevant parent font size. Nested em sizing can compound.

Worked example

<form id="converter">
<label for="px">Target font size in CSS pixels</label><br><input id="px" type="number" min="0" step="any" value="24" required><br>
<label for="base">Parent font size in CSS pixels</label><br><input id="base" type="number" min="0.01" step="any" value="16" required><br>
<button type="submit">Convert</button></form><p id="converted" role="status"></p>
<script>
const form = document.querySelector("#converter");
form.addEventListener("submit", event => {
  event.preventDefault();
  const px = Number(document.querySelector("#px").value), base = Number(document.querySelector("#base").value);
  document.querySelector("#converted").textContent = Number.isFinite(px) && Number.isFinite(base) && px >= 0 && base > 0 ? (px / base).toFixed(4).replace(/\.?0+$/, "") + "em" : "Enter a non-negative target and a positive parent size.";
});
</script>

For a 24px target with a 16px parent, the result is 1.5em. This is a font-size conversion relative to the parent, not a universal measurement for every property.

Practice

Convert a 20px font size with a 16px parent, and explain what changes if the parent becomes 20px.

Show a suggested answer
20 / 16 = 1.25em. With a 20px parent, 1.25em produces 25px instead of 20px.

Common mistake

Do not assume the base is always 16px or divide by zero. The correct base depends on the actual inherited size.

HTML documentation

Live Example

Try Coding

Result