CSS Units: px / em / rem 🤯

Laura Beatris
Laura Beatris
Published in
2 min readJun 7, 2019
Photo of https://www.youtube.com/watch?v=2B_uJhpSIC4

Why we should start to use these units in your projects?

→ First: You might think, what’s wrong with using pixels? The answer is that you have always to remember about the users and how can we improve their navigation. Knowing that the browser has a default font-size (Typically 16px) and the user can just change to a different size, 20px for example, those elements that were set with pixels won’t change.

→ I really recommend this video about CSS Units and Box Dimension 🤯: https://www.youtube.com/watch?v=2B_uJhpSIC4

REM 👩‍🎨

REM is used for setting font-sizes with values based on the font-size of the root <html> element. So we can scale our project just changing the root font-size.

Imagine if the font-size of our <html> element is 10px then 1rem = 10px. So if a set 2rem to a paragraph — 2 * 10px = 20px.

If the size of a box is based on the font-size of the <html> element, so we set the width and height with the rem unit.

But there’s a problem with setting root font-size with pixels, the good practice is to use percentage. As we know, usually the default font-size of the browser is 16px, setting the font-size: 100% — 1 rem = 16px. But we can improve this setting the font-size: 62.5% of 16px that is 10px, so 1rem = 10px.

CSS pre-processors (SASS/SCSS/LESS) 🙃

In CSS pre-processors you can use functions to calculate these things. So be thankful for that.

EM

An em is equal to the font-size of the element’s parent. If you set a <div> with 16px than all of its children will be defined with 1em = 16px;

A good way of use em is with sidebars and with media queries.

These units may look difficult in the first contact but after practicing it will be easier and make your site look better.

--

--

Laura Beatris
Laura Beatris

Software Engineer and Content Creator | Mentor at Rocketseat | React.js and GraphQL Enthusiast