damian
damian

Reputation: 5444

Define variables in Sass based on classes

I'd like to know if it's possible to define a variable in Sass depending on if a class is set or not. I need to do some font type tests and would like to change the font-variable $basicFont dynamically based on the body class.

E.g.:

$basicFont: Arial, Helvetica, sans-serif;

body {
    &.verdana {
        $basicFont: Verdana, sans-serif;
    }
    &.tahoma {
        $basicFont: Tahoma, sans-serif;
    }    
}

Is there a possibility to handle this in Sass?

Upvotes: 4

Views: 2133

Answers (1)

cimmanon
cimmanon

Reputation: 68319

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;
}

Upvotes: 4

Related Questions