Font Size units in CSS

3 commonly used units for font sizes in CSS, explained in short!

Table of contents

Pixel(px), Rem and Em are the 3 units that I use on a daily basis for setting font-sizes on CSS stylesheets, let's take a closer look at each one.

Pixel


A pixel(px) value is independent of the OS and is more or less consistent across browsers. It is basically a way of specifying the exact font-size you want your element to be rendered at.

When I first started off with CSS, I was using pixels to set the font-size for elements left, right and center. It is usually the first unit that beginner web-development courses touch upon and I saw no reason to use anything else.

This was before I knew what accessible web design meant.

Once you set the font-size for an element in terms of pixels, it cannot be changed in (some) browsers i.e it is a static value. This can severly hamper accessibility for vision-impaired users who might change the font-size so that they can better view the content.

Rem


What is 1 rem? 1 rem is equivalent to the root font-size of the browser i.e the root html element. Most browsers today have the default font-size set to 16px, so 1 rem equals 16px by default.

To change the root font-size, you can change the font-size of the html element as follows:

html { font-size: 62.5% }

which changes the root font-size to 10px (62.5% of 16px).

As the user scales the font-size up and down according to his/her requirement, anything sized using the rem unit will scale up and down accordingly (since the root font-size increases/decreases).

All things considered, my unit of choice for setting font-sizes is the rem unit due to it's simplicity and ease of use.

Em


The em unit is similar to rem but with certain caveats. How much does 1 em equal? 1 em when set on an element equals the font-size of it's nearest ancestor (which has it's font-size set).

If none of the element's ancestors have a font-size set, it inherits the root font-size of the browser.

The em unit suffers from a problem called compounding. Consider the following piece of HTML and corresponding CSS.

image.png

div { font-size: 10px } p { font-size: 2em }


The font-size for the outer p tag will be 2 em = 20px. 1 em will be equal to 10 px since it will inherit the font-size of the nearest ancestor where font-size is set i.e 10px (ancestor div's font size).

However, the font-size for the inner p tag will be 2 em = 40px. This is because the definition of 1 em will change for the inner p tag according to it's parent p's font-size. For the inner p tag, 1 em = 20px since it's nearest ancestor's (parent p tag) font-size is 20px.

Summary


Long story short, always use responsive units for your CSS font-sizes. Responsiveness and accessibility is the name of the game.

That's all about 3 commonly used font sizes in CSS. Hope this bit helped you :)