Last Updated: February 25, 2016
· yoeran

SCSS - Abstract font inclusion

Ever found yourself going through all of your SCSS files in order to replace a font with a prettier font you just found? Or did you anticipate this and have the font reference into a variable? Did you also account for the fact that your new font doesn't support that particular font-weight your previous font did?

I found myself struggling with this occasionally so I wrote a mixin that abstracts the font-family (and weight) from it's eventual purpose.

First setup your font stacks in a SASS Map (SASS 3.3 required)

@ import url(,700|Titillium+Web:600);

$fonts: (
    body: (stack: ('Open Sans', Arial, sans-serif), weights: (normal: 400, bold: 700)),
    headers: (stack: ('Titillium Web', Arial, sans-serif), weights: (normal: 600, bold: 600))

Then use it anywhere in your SCSS

body {
    @include font(body, normal);

h1 {
    @include font(headers, bold);

The result:

body {
    font-family: 'Open Sans', Arial, sans-serif;
    font-weight: 400;

h1 {
    font-family: 'Titillium Web', Arial, sans-serif;
    font-weight: 600;

The mixin

// Font setter through abstracted labels
@mixin font($fontLabel, $weightLabel) {
    $fonts: (body: (stack: 'Arial', weights:(normal: 400, bold: 600) )) !default;
    $fontWeight: 400;
    $fontStack: 'None';

    // Match given type with fontstacks
    @each $fontKey, $font in $fonts {
        @if $fontLabel == $fontKey {
            // get stack and weights
            @each $elem, $value in $font {
                @if $elem == 'stack' {
                    $fontStack: $value;

                @if $elem == 'weights' {
                    @each $weightKey, $weight in $value {
                        @if $weightKey == $weightLabel {
                            $fontWeight: $weight;

    // set CSS
    font-family: $fontStack;
    font-weight: $fontWeight;

1 Response
Add your response

I like it! It would be neat if you could include font-variants as well. I posted a similar protip for locally hosted @font-face tidying.

over 1 year ago ·