Compact @font-face
declarations in Sass
Sass supports defining and iterating over lists. A good use
case for these is when declaring @font-face
rules. Often a font family
is distributed in multiple files, one file for each style and weight
combination. For example:
% ls -1
PostGrotesk-Black.woff2
PostGrotesk-BlackItalic.woff2
PostGrotesk-Bold.woff2
PostGrotesk-BoldItalic.woff2
PostGrotesk-Book.woff2
PostGrotesk-BookItalic.woff2
PostGrotesk-Light.woff2
PostGrotesk-LightItalic.woff2
PostGrotesk-Medium.woff2
PostGrotesk-MediumItalic.woff2
PostGrotesk-Thin.woff2
PostGrotesk-ThinItalic.woff2
%
The @font-face
rules for this font family can be expressed compactly using
lists in SCSS syntax:
$faces:
normal 100 "Thin",
italic 100 "ThinItalic",
normal 300 "Light",
italic 300 "LightItalic",
normal 400 "Book",
italic 400 "BookItalic",
normal 500 "Medium",
italic 500 "MediumItalic",
normal 700 "Bold",
italic 700 "BoldItalic",
normal 900 "Black",
italic 900 "BlackItalic";
@each $style, $weight, $suffix in $faces {
@font-face {
font-family: "post grotesk";
src: url("/fonts/post-grotesk/PostGrotesk-#{$suffix}.woff2") format("woff2");
font-style: $style;
font-weight: $weight;
}
}
This should compile to the following CSS:
@font-face {
font-family: "post grotesk";
src: url("/fonts/post-grotesk/PostGrotesk-Thin.woff2") format("woff2");
font-style: normal;
font-weight: 100;
}
@font-face {
font-family: "post grotesk";
src: url("/fonts/post-grotesk/PostGrotesk-ThinItalic.woff2") format("woff2");
font-style: italic;
font-weight: 100;
}
@font-face {
font-family: "post grotesk";
src: url("/fonts/post-grotesk/PostGrotesk-Light.woff2") format("woff2");
font-style: normal;
font-weight: 300;
}
/* ... SNIP ... */