em and rem
Learn em and rem relative units.
The em unit
The em unit is relative to the font size. If you write font-size: 1.5em for an element, the browser takes 1.5 times the parent's font size.
em compounds when nested: each level is computed against its own parent. That is why you should be careful with nested menus.
The rem unit
rem (root em) is always computed against the html root font size. Write font-size: 1.25rem and the browser multiplies the root font size by 1.25.
Unlike em, rem does not compound; every rem value ties back to the same root. That makes rem the preferred choice for a steady, predictable scale.
em vs rem
em ties to the parent, rem ties to the root. In a nested list, em grows at each level; rem stays the same at every level.
That is why rem is preferred for typography and em for small scoping inside a component. Using both together is common.
Exercise em and rem for root and heading
Write two blocks: give the html selector font-size: 16px, and the .heading selector font-size: 1.5rem plus line-height: 1.2em.
Show example solution
/* add root and heading styles */
html {
font-size: 16px;
}
.heading {
font-size: 1.5rem;
line-height: 1.2em;
}
Test yourself
-
What does rem reference?
/* rem locks to the root */- The parent's font size
- The screen width
- The html root font size
- The viewport height
Show answer
The html root font size — Correct. rem always references the html root font size; it does not compound.
-
Font size with rem
.heading { font-size: ____rem; }Show answer
.heading { font-size: 1.5rem; } -
Match each unit to its reference
- em
- Parent font size
- rem
- Root font size
- px
- Fixed pixel
- vw
- Viewport width