CSS Solid

Relative unit (em)

‘em’ is a font size. It relates to base or parent element font size.

Ex: 1em = font size of the base or parent element.

Note: Browsers default font size is typically 16px.

Example 1: Set font size and line height to the P element(s) using relative unit (em).


<!DOCTYPE html>
<html>
<head>
    <title> CSS Relative Unit (em) </title>
    <style>
        p {
            font-size: 2em;
            line-height: 1.2em;
            border: 1px solid green;
        }
    </style>
</head>
<body>
    <p> First Line</p>
    <p> Second Line</p>
</body>
</html>

Result:

In the above example,

  • By default, browser default font size (16px) is applied to all elements. Body element is base or parent to the P elements.
  • Font size 2em ( 2 * 16px = 32px) is applied to each P element.
  • Line height 1.2em (1.2 * 16px = 19.2px) is applied to each P element.

Example 2: Set font size DIV element using relative unit (em).


<!DOCTYPE html>
<html>
<head>
    <title> CSS Relative Unit (em) </title>
    <style>
        #parent {
            font-size:16px;
        }
        #child {
            font-size:2em;
        }
    </style>
</head>
<body>
    <div id="parent">
        DIV element - Parent
        <div id="child">
            DIV element - Child
        </div>
    </div>
</body>
</html>

Result:

In the above example,

  • Parent DIV element (id="parent") font size is 16px.
  • Child DIV element (id="child") font size is 2em (2 * 16px = 32px).
  • Child DIV element font size is related with parent DIV element font size.