Last Updated: September 09, 2019
·
2.154K
· drrobotnik

Absurdly Abstract @font-face mixin

Branded fonts are a pain

We need to account for font weights. Not every font has every weight, so we need a clean way to define the ones we have.

I usually have at least these two files included in my main styles.scss file:

  • _vars.scss
  • _mixins.scss

Then, within _vars I add my list variables:

$brand-faces:
   'Nexa' (
        normal "nexa/nexa_regular-webfont",
        bold "nexa/nexa_bold-webfont",
        bolder "nexa/nexa_black-webfont"
    ),
   'TinFish' (
        bold "font/tin-fish",
        lighter "font/tin-fish",
        normal "font/tin-fish"
    );

Wow! Thats some clean definition... Notice that they don't even need to be in any particular order! If you're not familiar with SASS lists, they can be multi-dimensional. Each definition could be on one line but I indented for clarity.

Inside of mixins.scss we have:

$brand-faces: false!default;

This default variable sets it so that the mixin isn't called if the variable isn't included.

@mixin brand-faces() {

    @each $face in $brand-faces {
        $face-name: quote( #{nth($face, 1)} );
        $font-weights: nth($face, 2);
        @each $weight in $font-weights {
            @font-face {
              font-family: $face-name;
              src: url( nth($weight, 2) + '.eot?76871668' );
              src: url( nth($weight, 2) + '.eot?76871668#iefix') format('embedded-opentype'),
               url( nth($weight, 2) + '.woff?76871668') format('woff'),
               url( nth($weight, 2) + '.ttf?76871668') format('truetype'),
               url( nth($weight, 2) + '.svg?76871668#rosche') format('svg');
              font-weight: nth($weight, 1);
              font-style: normal;
            }
        }
        .font-#{nth($face, 1)} {
            font-family: $face-name;
        }
    }

}

The mixin itself. Here we create the font name and all it's weight variations based on the $brand-faces list.

@if $brand-faces != false {
    @include brand-faces();
}

And this is where we check if the variable is set.

If all was set well

You should have an output of all the font weights. The output is too long for a protip so if you're interested, take a look at this gist

You may have noticed I ignored font-style which is equally important! If anyone has an addition for font styles that is piggybacks on the method above, let me know.

2 Responses
Add your response

This is AWESOME.

over 1 year ago ·

Thanks!

over 1 year ago ·