em vs rem

1 minute read

TIL the difference between em and rem in CSS.

I found the em-vs-rem blog post on zellwk.com to be helpful in cementing my understanding. Read there for more detail.

The Difference

em: equivalent to the font-size of the nearest parent. If an element has font-size of 12px, 1em for that element and any direct children of that element is 12px.

rem: equivalent to the font-size of the root element. If the root element has a font-size of 14px 1rem for all elements on the page is 14px.

The default font-size in a browser is 16px. Therefore if no font-size is explicitly set for any elements in your layout, 1em and 1rem will both be equal to 16px.

em and rem can be used to scale padding, margin, and other pixel based CSS properties. Using em and rem to perform text spacing will make your UI respond to changes in font-size. This can be advantageous, since changing the font-size won’t require additional work to resize padding, margins, and other layout properties: they will just auto-scale based on the font-size of the page!

Application on the Site

Understanding em was useful when styling the TIL counter at the top of my TIL page. At small screen widths, the font-size of my h3’s scale down from 20px to 16px. I had explicitly defined a 20px font-size for my TIL counter, which is a child of the h3. Since I used an explicit pixel number, the font size of my counter did not scale with the rest of the text, and as a result it looked large and out of place on small screen sizes.

I changed the font-size of my counter to be 1em: in other words, equivalent to the font-size of the direct parent (which in this case is the h3 which has font-size of 20px at large screen widths and 16px at small screen widths).

This example really hammered home the importance of using relative measurements like em and rem when laying out your text.

Tags:

Categories:

Updated:

Leave a Comment