Search code examples
cssnormalize

Calculating REM, EM and PX values in normalize.css for font sizing and margins etc


I've recently become a big fan of normalize.css

In the past, I've used this super easy method to calculate my font sizes, line height, margin and padding calculations. However, the sizing structure via normalize.css is completing confusing me.

For example. Via the body tag, font-size is being calculated in REMs and PX and line-height is being calculated in unitless values:

body,
button,
input,
select,
textarea {
    font-size: 16px;
    font-size: 1rem;
    line-height: 1.5;
}

Whilst margins and padding is being calculated in EMs:

p {
    margin-bottom: 1.5em;
}

How is everything being calculated? Let's say I want to add a margin of 24px to my <p> tag. This is not a method I've come across before and it's important I understand the logic so I can correctly calculate everything. Any links you can provide to further reading is greatly appreciated.


Solution

  • In your sample

    The em and ex units depend on the font and may be different for each element in the document. The em is simply the font size.

    All you need to know is here: https://www.w3.org/Style/Examples/007/units.en.html

    Since em is the body's set font, this will give 24px margin

    body {
      font-size: 16px;
    }
    div {
      height: 30px;
      background: red;
    }
    p {
      background: yellow;
      margin-bottom: 1.5em;
    }
    <p>Hello</p>
    <div></div>

    And this will give 45px margin

    body {
      font-size: 30px;
    }
    div {
      height: 30px;
      background: red;
    }
    p {
      background: yellow;
      margin-bottom: 1.5em;
    }
    <p>Hello</p>
    <div></div>