LoginSignup
281
222

More than 5 years have passed since last update.

CSS3のremとemの違いについて

Last updated at Posted at 2017-11-04

CSSのフォントサイズ指定方法は次の2つ

  • 絶対値: 10pxなら絶対に10px
  • 相対値: 親要素のサイズによって可変

px

  • サイズを絶対値で指定
html {
  font-size: 32px;
}

h1 {
  font-size: 64px; /* -> 64px; */
}

span {
  font-size: 20px; /* -> 20px; */
}

em

  • 親要素のfont-sizeを基準に大きさを計算する
html {
  font-size: 32px;
}

h1 {
  font-size: 2em; /* -> 64px; */
}

span {
  font-size: 0.5em; /* -> 32px; */
}

%

  • emと同じで親要素の相対値
html {
  font-size: 32px;
}

h1 {
  font-size: 200%; /* -> 64px; */
}

span {
  font-size: 50%; /* -> 32px; */
}
  • 要素が入れ込んでくると、どの親要素を基準にしているかが分かりにくくなる
  • そのためCSS3で使えるようになったのが、rem

rem (root em)

  • 文書のルート要素、つまりhtml要素のfont-sizeを基準にする
html {
  font-size: 32px;
}

h1 {
  font-size: 2rem; /* -> 64px; */
}

span {
  font-size: 0.5rem; /* -> 16px; */
}

ブラウザサポートを確認

  • Can I Useで確認するとIE8以下は未対応。IE9と10は一部対応
  • それ以外のブラウザは対応している

Kobito.qvcwUf.png

ブラウザのデフォルトサイズ

  • 16px
html {
  font-size: 100%; /* -> 16px; */
}

pxだとなぜいけないのか

  • ブラウザによって文字の大きさが変わる
  • あなたはどれにする?CSSの文字サイズ指定「px、em、%」 – デザインメモ http://blog.karasuneko.com/3092/

よくあるやり方

html {
  font-size: 62.5%; /* -> 10px; */
}
  • デフォルトの16pxの代わりに1emが10pxになるように調整
body {
  font-size: 1.4em; /* -> 14px; */
}
  • 上の設定により「px」を使用するのに似た感覚でフォントサイズを指定できるようになる
  • bodyでemを使うのはChromeのバグ対応
.page-header {
  font-size: 2rem;

  • emは親のfont-sizeに相対的で入れ子の時に問題になる
281
222
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
281
222