0
0
CssConceptBeginner · 3 min read

What is em in CSS: Explanation and Usage

em in CSS is a relative unit of measurement that scales based on the font size of the parent element. It helps create flexible layouts and text sizes that adjust naturally to different screen sizes and user settings.
⚙️

How It Works

Think of em as a way to measure size relative to something you already know — the font size of the parent element. If the parent text is 16 pixels, then 1em equals 16 pixels. If you set a child element’s font size to 2em, it will be twice as big as the parent’s font size, or 32 pixels.

This is like using your shoe size to decide how big your socks should be. If your shoe size changes, your sock size changes too, keeping everything proportional. This makes em very useful for responsive design because sizes adjust automatically when the base font size changes.

💻

Example

This example shows how em units scale with the parent font size.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>em Unit Example</title>
  <style>
    body {
      font-size: 16px;
    }
    .parent {
      font-size: 20px;
      border: 1px solid #333;
      padding: 1em;
      margin: 1em;
    }
    .child {
      font-size: 1.5em; /* 1.5 times parent font size = 30px */
      color: darkblue;
    }
  </style>
</head>
<body>
  <div class="parent">
    Parent text (20px)
    <div class="child">Child text (1.5em = 30px)</div>
  </div>
</body>
</html>
Output
A box with border containing text 'Parent text (20px)' in 20px font size and inside it, blue text 'Child text (1.5em = 30px)' in larger font size (30px).
🎯

When to Use

Use em when you want sizes to scale relative to the current font size, making your design flexible and accessible. It is great for setting font sizes, padding, margins, and spacing that should grow or shrink with text size changes.

For example, if a user increases their browser’s default font size for readability, elements sized with em will adjust accordingly, improving usability. It’s also helpful in components where child elements should scale based on their container’s font size.

Key Points

  • em is relative to the font size of the parent element.
  • It helps create scalable and responsive designs.
  • Using em improves accessibility by respecting user font size preferences.
  • It can be used for fonts, spacing, and layout dimensions.

Key Takeaways

em units scale relative to the parent element’s font size.
They help make text and layout sizes flexible and responsive.
Using em improves accessibility by adapting to user settings.
em can be used for fonts, padding, margins, and more.
Remember 1em equals the current font size of the parent element.