【问题标题】:Define variables in Sass based on classesSass中基于类定义变量
【发布时间】:2014-04-04 13:43:19
【问题描述】:

我想知道是否可以根据是否设置类在 Sass 中定义变量。我需要做一些字体类型测试,并想根据正文类动态更改字体变量$basicFont

例如:

$basicFont: Arial, Helvetica, sans-serif;

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

有没有可能在 Sass 中处理这个问题?

【问题讨论】:

    标签: sass


    【解决方案1】:

    没有。您所要求的将需要 Sass 了解 DOM。 Sass 只直接编译成 CSS,它从不发送到浏览器。

    使用您的示例代码,您所做的只是每次都覆盖$basicFont。在 3.4 或更高版本中,您的变量将仅存在于设置它的块的范围内。

    因此,您唯一真正的选择是使用 mixins 或扩展。

    扩展

    这是有效的,但只适用于非常简单的情况。

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

    输出:

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

    混音

    如果您想要更细粒度地控制在何处使用哪些变量,这是我推荐的方法。

    $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');
            }
        }
    }
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 2021-04-29
      • 2012-10-30
      • 2012-04-12
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      相关资源
      最近更新 更多