How to Use EM and REM
Both em
and rem
are CSS size and dimension units. Each is determined by a font size.
The value of 2em is calculated as twice the font size used by the current element. The value 2rem is calculated as twice the size of the document's root font.
If you specify a font size for the html
tag, then that font size will be the root font size and will be used for rem
calculations. Otherwise, the reader's browser default font size will be used for rem
(generally 16px, but may be changed in the user's browser settings).
Example of font size specification for html
tag:
<style> html { font-size:20px; } </style>
Here is an example of a rem
unit and an em
unit being used in an element with a different font size.
<div style="font-size:32px;"> <p style="margin-left:1rem;">Testing REM</p> <p style="margin-left:1em;">Testing EM</p> </div>
In the above example, the rem
unit is calculated using root font size 20px, resulting in a 20px left margin indent, and em
is calculated using font size 32px, resulting in a 32px indent.
Testing REM
Testing EM
The published font size is the same for both paragraphs. But the indents using rem
and em
are calculated using different font sizes.
My own use of rem
tends to be for between-line spacing of lines published with different font sizes. When lines with different font sizes (such as an h1
line and an h4
line) have margins specified as em
the spacing will vary depending on the line's font size. With rem
, the spacing is consistent.
<h1 style="margin:1rem 0;">Header 1</h1> <h4 style="margin:1rem 0;">Header 4</h4> <p style="margin:1rem 0;">Paragraph line</h1> <h1 style="margin:1rem 0;">Header 1</h1>
The line spacing with the above renders like this.
Header 1
Header 4
Paragraph line
Header 1
The things to remember for a simple concept is that the "r" in rem
means "root". The rem
unit comes from the root font size. The em
unit comes from the current font size — the size the current element is using.
(This article first appeared with an issue of the Possibilities newsletter.)
Will Bontrager