Calculating EMs with SCSS

05-08-2012

Earlier this year Erskine made the switch to SCSS and I’ve really loved what its done to our front-end workflow. One thing I’m particularly fond of is how SCSS has improved how we’re calculating EMs.

The olden days

Before SCSS we’d simply make our EM calculation and leave a comment explaining where that number came from off to the side. This worked fine, but could be time consuming and was a nightmare when adjusting things like, say, our base-font.

Here’s an example:

h1 {
font-size:1.875em; /* 30 / 14 */
}

Using SCSS for calculations

To calculate EMs with SCSS we have a few options; using the basic number operations or definining our own function, to name a few.

Basic number operations

Using basic number operations we can drop the commenting that is needed with standard CSS and used the code as documentation. This is the technique we originally used when we switched to SCSS. This works, but we can do much better:

h1 {
font-size:(30 / 14) * 1em;
}

Defining our own EM calculation function

SCSS has tons of built in functions for common calculations, and we can even make our own. Here’s a function we’re using to calculate EMs, which is a modification of one we found in The SASS Way.

@function em($target, $context: 14) {
@return ($target / $context) * 1em;
}

This function takes 2 variables, $target and $context. $context is optional, as it defaults to 14, our base-font. Now lets rewite our example using our new function:

h1 {
font-size:em(30);
}

This is the same as saying (30 / 14) * 1em but now we don’t have to repeat ourselves all over the stylesheet.

But wait, this can be taken a step further.

Adding variables to our EM calculation. Vuala!

We can modularise this process more by defining default variables for our base-font size, heading sizes, etc. With these in place, tasks like “adjusting the base-font” can be done in a matter of seconds.

$basefont:14;
$baseh1:30;

@function em($target, $context: $basefont) {
@return ($target / $context) * 1em;
}

h1 {
font-size:em($baseh1);
}

Beautiful. Checkout the SCSS config file in Erskine’s Ultimate Package for more examples of how you can take advantage of default variables in SCSS.