clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

SCSS @font-face mixin

Filed under: Styling— Tagged with: typography, sass

The built-in Compass mixin is bit janky, here’s better.

@mixin font-face($style-name, $file, $family, $category: '') {
  $filepath: 'fonts/' + $family + '/' + $file;

  @font-face {
    font-family: '#{$style-name}';
    src: url($filepath + '.eot');
    src: url($filepath + '.eot?#iefix') format('embedded-opentype'), url($filepath + '.woff')
        format('woff'), url($filepath + '.ttf') format('truetype'), url($filepath + '.svg#' + $style-name + '')
        format('svg');
  }

  %#{$style-name} {
    font: {
      @if $category != '' {
        family: '#{$style-name}', #{$category};
      } @else {
        family: '#{$style-name}';
        weight: normal;
      }
    }
  }
}

Use it like this:

@include font-face($style-name, $file, $family, $category);
  • $style-name being the name of the font e.g. Helvetica
  • $file meaning the file name, without the file extensions
  • $family being the folder inside the fonts folder where the font files are
  • $category is serif or sans-serif or monospace etc. as a fall back in CSS

Here with real values:

@include font-face('Ashbury', 'AshburyLig-webfont', 'Ashbury', 'serif');

It'll output:

@font-face {
  font-family: 'Ashbury';
  src: url('fonts/Ashbury/AshburyLig-webfont.eot');
  src: url('fonts/Ashbury/AshburyLig-webfont.eot?#iefix') format('embedded-opentype'),
    url('fonts/Ashbury/AshburyLig-webfont.woff') format('woff'),
    url('fonts/Ashbury/AshburyLig-webfont.ttf') format('truetype'), url('fonts/Ashbury/AshburyLig-webfont.svg#Ashbury')
      format('svg');
}

More info and source.

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!