I love rem. I’ve been using it since I first read about it in Jonathan Snook’s article, and even more so since I started building responsive websites.
So what is rem?
Rem is a value that is relative to the root font-size, meaning the font-size that is set on the <html>
element. The browser by default sets the font-size at the root to 16px.
There are some articles around about why rem is good and super handy, so I won’t go into too much detail here. But in short, rem is awesome because:
- It works like pixels in that you don’t get compounding issue like you do with em and the computed value is always the same no matter where the value is set.
- It is better accessibility wise as it can be scaled like em, so users can resize the text on the page.
- In responsive design, you can set a different font-size on the
<html>
at each breakpoint and the text on your site will scale proportionally according to your root font-size.
The only “issue†with rem is that it’s not supported by older browsers, namely IE8 and lower. So to use it, you’ll need to include the font-size in px as a fallback. But in my eyes, its benefits outweigh this small “issue†by far.
Using rem in our projects
Since we started using Sass for our projects, to make things more convenient, we wrote a mixin that will convert the input px to rem. It also outputs the px value as fallback for browsers that don’t support rem.
Creating the function
So first step, we need to write a Sass function that gets the rem value based on the px value that has been passed in. To do this, we need to divide the input px value with the default 16px set by the browser:
@function calculateRem($size) {
$remSize: $size / 16px;
@return #{$remSize}rem;
}
You might ask, “What if the user has a different default font size in their browsers”? Well, the great thing about rem is that the text will just scale proportionally like em! Pretty good, right?
Creating the mixin
Next we create a mixin that calls the function:
@mixin fontSize($size) {
font-size: $size; //Fallback in px
font-size: calculateRem($size);
}
Now your mixin is ready to be used! To use it, simply include the mixin wherever you need to declare a font-size.
Sass:
h1 {
@include fontSize(32px);
}
Output:
h1 {
font-size: 32px;
font-size: 2rem;
}
With simple Sass functions and mixins like this, we save a ton of time and human errors from punching numbers into our calculators.
You can find all the code to convert rems from pixels on the OOCSS open source project.