Dan Devine Dan Devine - 3 months ago 10
CSS Question

Sass control directives to add attribute to elements with existing attribute

I'm referring to the documentation here:

sass docs

and trying to see if its possible to use an if statement to apply a letter spacing attribute to each class that uses a certain font family.

I've tried

h1 {
@if font-family == 'Open Sans Condensed' {letter-spacing: 0.1em;}
}

h1 {
font-family: 'Open Sans Condensed', sans-serif;
}


with the hope of outputting:

h1 {
font-family: 'Open Sans Condensed';
letter-spacing: 0.1em;
}


which doesn't work. i'm pretty sure that I'm approaching this problem from the wrong angle. Can anybody verify if this kind of usage is possible?

Answer

Two ways you could approach this:

1) Include the letter-spacing as part of the font-face definition.

@font-face {
  font-family: 'Open Sans';
  src: [urls for various formats go here];
  letter-spacing: 0.1em;
 }

If you're loading the font in from an external stylesheet, like with google fonts or similar, you should still be able to declare a second font-face block that just includes the font-family and letter-spacing rules.

2) Use a sass mixin. You can make it very simple or more flexible, depending on whether you want to account for multiple fonts.

Basic one-font setup:

@mixin font-styles() {
  font-family: 'Open Sans Condensed', sans-serif;
  letter-spacing: 0.1em;
}

h1 {
  @include font-styles;
}

Or parameterized for multiple font styles:

@mixin font-styles($font: 'headings') {
   @if $font == 'headings' {
     font-family: 'Open Sans Condensed', sans-serif;
     letter-spacing: 0.1em;
   }
   @elseif $font == 'text' {
      font-family: 'Open Sans', sans-serif;
      [related font styles go here]
   }
   [add more font style sets as needed]
}

h1 { @include font-styles('headings'); }
p { @include font-styles('text'); }
Comments