Hone

Lessons · HTML and CSS · px, rem, em and %

px, rem, em and %

px is fixed. rem is relative to the root font size. em is relative to the element's own font size, so it compounds through nesting. % is relative to the parent.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Picking the unit is picking what a size follows: the screen, the reader's text setting, the parent, or nothing. Most layout bugs on phones are a fixed unit where a relative one belonged.

How to think about it

rem for font sizes and spacing, % or fr for widths, em only for things that should scale with their own text, px for borders and the odd one-pixel line.

Worked example

html { font-size: 16px; }
The root size; rem measures from here.
<div class="a">2rem<div class="b">1.5em inside it</div></div><p class="c">Half width</p>
A box, a nested box, and a paragraph.
.a { font-size: 2rem; }
32px, whatever surrounds it.
.b { font-size: 1.5em; }
Relative to its parent's 32px: 48px. em compounds; rem would not.
.c { width: 50%; }
Half of the parent's width, whatever the screen.

Your turn

Size the heading from the root, not the parent.

h2 { font-size: 1.5; }

The trap

em on nested elements. A list inside a list inside a list, each at 1.2em, ends up at 1.73 times the size, and nobody can see why.

Practise px, rem, em and % on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.