Define variables in Sass based on classes

后端 未结 1 868
遥遥无期
遥遥无期 2020-11-28 15:11

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-v

相关标签:
1条回答
  • 2020-11-28 15:18

    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;
    }
    
    0 讨论(0)
提交回复
热议问题