Last Updated: February 25, 2016
·
3.291K
· johncionci

Font Sizing with REM in SCSS

We just started using CSS preprocessors here at the office ( yeah were a bit late to the party ). We decided that SCSS was the way to go and lean on the Compass library for the most part.

Current versions of WordPress theme stress the importance of using REMs going forward for font-sizing, always with a pixel fallback.

When I researched this on the Compass site I found their was a lot of back-and-forth discussion and no real support built in. So I decided to whip up my own.

$base_font_size: 16;

@mixin font($pixels, $weight : normal) {
font-size: $pixels + px;
font-size: ( $pixels / $base_font_size ) + rem;
font-weight: $weight;
}

And we include it this way.

@include font(14, bold);

And we get this!

font-size: 14px;
font-size: 0.875rem;
font-weight: bold;

We basically take whatever the pixel value should be, divide that by our base font size ( ie. 16 ) and automagically spit out our REM value with our pixel fallback.

We have also defined the font-weight, our default is normal but in the case that we need to have bold or override the option is available.

1 Response
Add your response

Nice work, and good to see you guys jump on the Compass bandwagon. Fun stuff.

In one of my Pro Tips I show a function that includes "unitless". Essentially, this is a check that you can make in case an author adds "px" to the values of the mixin. If they do, you can check for that, and not add the "px" if it is already present.

I like this, personally, as I like to see units as much as possible in my SCSS. It reinforces how things are working, while unitless values (integers) seem scary... as in, "What did '24' in this context mean again? Pixels? Ems? Percents?" I like to avoid that confusion whenever possible.

over 1 year ago ·