EM

A relative unit based on the font size of the element’s parent element. 1em equals the parent’s font size.

Example: (Sets the h1 heading to twice the size of the parent element’s font size)

h1 { 
font-size: 2em;
}

Usages

  • Font sizes: Defining font sizes relative to the parent’s font size for easier scaling and creating typographic hierarchies.
  • Responsive typography: Allows font sizes to adjust proportionally with the base font size.

Example: The example showcases the units responsive behavior.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" 
        content="width=device-width, initial-scale=1.0">
  <title>Unit Comparison</title>
  <style>
    body {
      font-family: sans-serif;
      margin: 0;
      padding: 0;
      background-color: rgb(100, 248, 100);
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    h1 {
      margin-top: 50px;
      color: white;
    }

    .container {
      /* Fixed size of the container */
      width: 800px;

      /* Font size of the container changes with 
         respect to 2% of viewport width */
      font-size: 2vw;

      text-align: center;

      padding: 20px;

      margin-top: 50px;

      outline: 2px solid white;
    }

    .heading-px {
      /* px is fixed size and is not 
         related to parent(.container) */
      font-size: 50px;

      color: blue;

      margin-bottom: 10px;
    }

    .heading-em {
      /* em is relative to parent(.container) font size */
      font-size: 2em;

      color: red;

      margin-bottom: 10px;
    }

    .heading-perc {
      /* % is relative to parent(.container) 
         font size 100% is same as 1em */
      font-size: 100%;

      color: darkcyan;
    }
  </style>
</head>

<body>
  <h1>Difference between px, %, and em units in CSS</h1>
  <div class="container">
    <h1 class="heading-px">This is a heading (px)</h1>
    <h2 class="heading-em">This is another heading (em)</h2>
    <h3 class="heading-perc">This is a smaller heading (%)</h3>
  </div>
</body>

</html>

Output:

Output



Difference Between px % & em Units in CSS

CSS units can be confusing to deal with as they are used in width, height, fonts and various other properties. You may have thought about which is the appropriate unit to use in a particular situation. we will discuss about the difference between px, %, and em units in CSS.

Similar Reads

Pixels-px

An absolute unit representing a single pixel on the user’s device screen....

Percentage-%

A relative unit representing a percentage of the containing elements’ size....

EM

A relative unit based on the font size of the element’s parent element. 1em equals the parent’s font size....