Define variables in Sass based on classes

No. What you’re asking for would require Sass to have knowledge of the DOM. Sass only compiles directly to CSS, it is never sent to the browser.

With your sample code, all you’re doing is overwriting $basicFont every time. In version 3.4 or later, your variable will only exist within the scope of the block where it was set.

So, your only real options are to make use of mixins or extends.

Extend

This is effective, but is only suitable for very simple cases.

%font-family {
    &.one {
        font-family: Verdana, sans-serif;
    }

    &.two {
        font-family: Tahoma, sans-serif;
    }
}

.foo {
  @extend %font-family;
}

Output:

.one.foo {
  font-family: Verdana, sans-serif;
}
.two.foo {
  font-family: Tahoma, sans-serif;
}

Mixin

This is the method I would recommend if you want a little more fine grained control over which variables are used where.

$global-themes:
    ( '.one': ('font-family': (Verdana, sans-serif), 'color': red)
    , '.two': ('font-family': (Tahoma, sans-serif), 'color': blue)
    );

$current-theme: null; // don't touch, this is only used by the themer mixin

@mixin themer($themes: $global-themes) {
    @each $selector, $theme in $themes {
        $current-theme: $theme !global;
        &#{$selector} {
            @content;
        }
    }
}

@function theme-value($property, $theme: $current-theme) {
    @return map-get($theme, $property);
}

.foo {
    @include themer {
        font-family: theme-value('font-family');

        a {
            color: theme-value('color');
        }
    }
}

Output:

.foo.one {
  font-family: Verdana, sans-serif;
}
.foo.one a {
  color: red;
}
.foo.two {
  font-family: Tahoma, sans-serif;
}
.foo.two a {
  color: blue;
}

Leave a Comment

tech