LoginSignup
2
1

More than 1 year has passed since last update.

「px」と「em」と「rem」の違い

Last updated at Posted at 2021-06-10

「px」

→絶対単位。
親要素の影響を受けずに、どんな状況でも指定したpxになる。
ユーザー操作による文字サイズの拡大/縮小に対応できなかったり、タブレットやスマートフォンなどの高解像度のディスプレイで表示をした場合、端末ごとに見た目の文字サイズが異なって表示されたりする場合がある。

「em」


→相対単位。
親要素のフォントサイズを基準とする。
<div class="box">
    <p class="text">テキストテキストテキスト</p>
</div>
html {
    font-size: 16px;  /* 1em = 16pxとなる。 */
}
.box {
    font-size: 2em;  /* 16px × 2 = 32px */
}
.text {
    font-size: 1.5em;  /* 32px × 1.5 = 48px */
}

入れ子構造が深くなるとフォントサイズ指定がし辛くなる。

「rem」

→相対単位。
ルート要素(html)のフォントサイズを基準とする。

<div class="box">
    <p class="text">テキストテキストテキスト</p>
</div>
html {
    font-size: 16px;  /* 1rem = 16pxとなる。 */
}
.box {
    font-size: 2rem;  /* 16px × 2 = 32px */
}
.text {
    font-size: 1.5rem;  /* 16px × 1.5 = 24px */
}

font-size: 62.5%;って何?

フォントサイズの単位にremを使いたい場合、htmlのフォントサイズが16pxのままだと分かりづらい。

html {
    font-size: 62.5%;
}

16px(ブラウザの基本のフォントサイズ) × 0.625 = 10px

htmlのフォントサイズが10pxになるので、
1rem = 10pxに設定することがきる。
こうすることによって計算がしやすくなる。

例)
10pxにしたい場合 = 1.0rem
16pxにしたい場合 = 1.6rem
36pxにしたい場合 = 3.6rem

補足

アクセシビリティ的にフォントサイズのpx指定はNGらしい

2
1
0

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
2
1