3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CSSの基本単位として使うと便利なrem

Posted at

CSSでのフォントサイズ指定は「px」や「em」を使うのが一般的。
CSS3で追加された「rem」という単位がとても使いやすそうなので、使い方について調べてみた。

rem と em の違い

emが親要素を基準としたサイズであるのに対し、remはroot (根っこ)が基準となっています。簡単に言うとhtmlに指定されたフォントサイズを基準とした倍率

index.html
<html>
	<body>
		<div> ABCDEFG </div>
	</body>
</html>
style.css

html{
	font-size: 62.5%; /*10px*/
}
 
body{
	font-size: 1.5em;
}
 
div{
	font-size: 1.5em;
}

ABCDEFGの文字サイズ = 10px * 1.5 * 1.5 = 22.5px

emは親要素を基準とした単位なので、こういう計算になる。
次に、remを使った場合の挙動。

style.css

html{
	font-size: 62.5%; /*10px*/
}
 
body{
	font-size: 1.5rem;
}
 
div{
	font-size: 1.5rem;
}

ABCDEFGの文字サイズ = 10px * 1.5 = 15px
bodyに指定されたfont-size:1.5em;は無視して、htmlに指定された10pxを基準としたサイズが求められます。

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?