Last Updated: September 09, 2019
·
6.648K
· charca

(R)evolution of the 'em' unit: rem

The em unit is one of the pillars of elastic layouts.
Its value is defined by the font size of the element you're working on (or its parent element), so if this value changes for any reason (i.e. the user zooming in or out), all your em defined sizes will change accordingly.

So what's an em?
By default, on a web browser, 1em is equal to 16px.

By default? You mean I can change this?
Of course. You just have to define the font-size of your html element to be 62.5%. This computes to 10px, making it a lot easier to define the rest of your sizes in ems:


html { font-size: 62.5%; /* 10px / } p { font-size: 1.2em; / 12px */ } </code> </pre> Amazing! So what's wrong with ems? Nothing really, BUT there's a risk that you might want to be aware of: nesting stuff. Let's take a classic example of a dropdown menu, where you'll have markup with this pattern: ul > li > ul > li I might want to have all my li elements to have a font-size of 14px, so I'd do something like this: li { font-size: 1.4em; } </code> </pre> Now, for my top level list items this would work as expected since their parent font size is 10px, so 1.4em = 14px. Perfect. But now the child list items have a parent font-size of 14px instead of 10px, so now 1.4em = 19.6px. Not really what we wanted. The solution for this is to redefine the child li: li { font-size: 1.4em; /* 14px */ } li li { font-size: 1em; /* 14px */ } </code> </pre> Not really the type of code I want on my css... and that's where the rem unit comes in. What's a rem? A rem unit (root em</code>) follows the same concept as the em, but with a small big difference. Instead of having its value defined by its parent's font-size, it takes the value from the root element's font-size; that is, in a HTML document, the html element. Let's code our example dropdown with rems: html { font-size: 62.5%; /* 10px / } li { font-size: 1.4rem; / 14px */ } </code> </pre> Now it doesn't matter how deep I'd go nesting stuff, 1rem will always be equal to 10px. What about browser support? It's pretty good actually. Every modern browser support rems, including IE9. If you're supporting older versions of IE, a good fallback will be to define your font sizes in px before you define them in rems, this way every browser will use the units they understand.

4 Responses
Add your response

Good stuff, thanks for making this clear ;)

over 1 year ago ·

Good.

over 1 year ago ·

I've recently discovered the 'rem' unit myself. It's tremendously helpful when trying to keep a consistent vertical rhythm with the margin's below headings. If your body text has a line height of say 1.5em, simply set margin-bottom: 1.5rem for your h1-6.

over 1 year ago ·

very good explanation! tks

over 1 year ago ·