When do you use em and when do you use rem?
If you have ever asked this, you are like me :) So welcome.
Basically, to save you time here it is:
- If you want your font-size relative to the container's font-size, use em
- If you want your font-size relative to the 'root' (or html) element's font-size, use rem!
If you just stop reading now that might be sufficient, but if you are more curious, go on.
Example companion codepen: https://codepen.io/binodpanta/pen/RwLWRra
Basically your page should ideally always have a default font-size specified for the root, such as
This typically becomes 16px default for the base font size.
Now, if you use rems in your elements' styles you get a consistent scaling wrt this number! so if you do
div.someclass { font-size: 0.5rem; }
you are going to always get a nice scaled font size regardless of screen size. So all your fonts will scale relatively throughout the app!
If you had used 0.5em, your calculated font-size could be 8px, but it could also be 1/2 of whatever the container's font-size was. And if that was itself em based, well.....
Isn't that nice?
In an upcoming post, I will also describe how it's not just font-sizes, but how em vs rem work with padding and margin. It's probably not what you think!
Comments
Post a Comment