rem with Sass

Update 02/08/15: I should pay attention to how things should be written, I used to write it as SASS when it should have been Sass. I will be updating the codes below in a day or two but I need to test them first. Thanks to Hugo Giraudel for being so nice as to educate me from my Sass-y sins :D


At this point, you’ve probably figured out that despite the fact that we basic idea of breakpoints per device, your layouts would still pretty much flop because your font sizes are too small or you find yourself fixing the font sizes manually on each device widths. And it is te-di-ous! DRY is shaking its head.

Enter rem, I’ve always had a soft spot for em over pixels. During the elastic vs. fixed vs. fluid debacle, I’ve always been in camp elastic but the problem with em is it can get pretty confusing, specially with nested elements with different font sizes. Not having Sass or LESS to ease the computation is a factor, too, of course. But rem just makes it all so much better.

rem stands for root em (read up more from Jonathan Snook because I’m horrible at explaining things), in a nutshell, it has all the goodness of em but it will only depend on one factor, the base font size that’s declared on your body and/or html element. I’ve used it in a number of projects in the past with Sass, and it has made making sites more readable on mobile so much easier. No more multiple font-size declarations (most of the time)!

I’m sure there are tons of resources available for this particular topic, but I’d rather dump all of my notes in this site so I can get back to it easily. So let’s get down to business, shall we?

Making a variable out of the base font size is optional, but I prefer having one because my laziness knows no bounds! This way, I don’t have to declare the base font size twice, once in the body (you’ll see below) and in the function’s formula. The function’s pretty basic and self-explanatory, to use it, all you have to do is write @rem-calc(14px) as value, for example:

h1 {
  font-size:@rem-calc(36px);
}

our function will then convert it as (if the base font size is 18px):

h1 {
  font-size:2rem;
}

Don’t forget the px or it will throw an error. Honestly, I would have liked forpxto be optional but I’m so used to typing the values with either apx or % and, frankly, it’s a habit that I’d rather not break. Moving forward! Declare theinitial font sizes, one for the desktop and another for mobile, I haven’thad the chance to target anMBP retina but based on when I last used it, you won’t have a need for a separate font size for it.

It’s important to note that once you start with rem, you will have to use it for every element and every declaration where you’re using pixels, specially with height and width! Otherwise, there will be awkward situations where your text is much, much bigger than its container.

Well then, there you go. If you have a much better and easier way to use rem, feel free to leave a comment and let’s chat!