點燈坊

失くすものさえない今が強くなるチャンスよ

em vs. rem

Sam Xiao's Avatar 2021-12-30

Except for px, em and rem are popular units for font size.

Version

CSS 3

em

em000

The font size of 3 nested <div>s are bigger and bigger.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, init-scale=1.0">
  <title>HTML Lab</title>
</head>
<body>
  <div class="outer">
    CSS
    <div class="middle">
      CSS
      <div class="inner">
        CSS
      </div>
    </div>
  </div>
</body>
<style>
html {
  font-size: 16px;
}

.outer {
  font-size: 1.2em;
}

.middle {
  margin-left: 10px;
  font-size: 1.2em;
}

.inner {
  margin-left: 10px;
  font-size: 1.2em;
}
</style>
</html>

Line 9

<div class="outer">
  CSS
  <div class="middle">
    CSS
    <div class="inner">
      CSS
    </div>
  </div>
</div>

3 nested <div>.

Line 20

html {
  font-size: 16px;
}

The font size of the whole page is 16px.

Line 24

.outer {
  font-size: 1.2em;
}

.middle {
  margin-left: 10px;
  font-size: 1.2em;
}

.inner {
  margin-left: 10px;
  font-size: 1.2em;
}
  • Except for margin, the font size of 3 <div>s are all 1.2em
  • em is according to the parent element. That’s why the results are bigger and bigger

rem

em001

The font size of 3 nested <div>s are the same.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, init-scale=1.0">
  <title>HTML Lab</title>
</head>
<body>
  <div class="outer">
    CSS
    <div class="middle">
      CSS
      <div class="inner">
        CSS
      </div>
    </div>
  </div>
</body>
<style>
html {
  font-size: 16px;
}

.outer {
  font-size: 1.2rem;
}

.middle {
  margin-left: 10px;
  font-size: 1.2rem;
}

.inner {
  margin-left: 10px;
  font-size: 1.2rem;
}
</style>
</html>

Line 24

.outer {
  font-size: 1.2rem;
}

.middle {
  margin-left: 10px;
  font-size: 1.2rem;
}

.inner {
  margin-left: 10px;
  font-size: 1.2rem;
}
  • Except for margin, the font size of 3 <div>s are all 1.2rem
  • rem is according to the root element. That’s why the results are the same

Conclusion

  • r in rem means root