【问题标题】:SASS generates two separate rules for same class using extend and mixinsSASS 使用 extend 和 mixins 为同一个类生成两个单独的规则
【发布时间】:2018-08-19 12:36:00
【问题描述】:

在这个 SCSS 代码中,我使用 mixin btn-structure 和扩展 %red-color 来获取一个类下的所有声明,这与我的预期相反 SCSS 为同一类输出了两个单独的规则,如下面的输出所示:

%red-color{
  color: red }

@mixin btn-structure 
  ($text-case: null, $text-shadow: null, $decoration: none ){

display: inline-block;

  text: {
          decoration: $decoration;
            transform: $text-case;
            shadow: $text-shadow }

}

.link-btn{
  @include btn-structure($text-case: 'uppercase', $decoration: underline);
  @extend %red-color
}

输出

.link-btn {
  color: red;
}

.link-btn {
  display: inline-block;
  text-decoration: underline;
  text-transform: "uppercase";
}

我不希望 SASS 输出属于同一类的两个单独的规则,如果属于一个类,如何让 SASS 输出一个规则。

【问题讨论】:

    标签: sass scss-mixins


    【解决方案1】:

    这是 Sass @extend 的实际行为和用例。

    说明

    为了清楚起见,更新您的代码如下

    %red-color{
      color: red
    }
    
    @mixin btn-structure ($text-case: null, $text-shadow: null, $decoration: none ){
      display: inline-block;
      text: {
        decoration: $decoration;
        transform: $text-case;
        shadow: $text-shadow 
      }
    }
    
    .link-btn{
      @extend %red-color;
      @include btn-structure($text-case: 'uppercase', $decoration: underline);
    }
    
    .test-class{
      @extend %red-color;
      @include btn-structure($text-case: 'uppercase', $decoration: underline);
    }
    

    这会编译为,

    .link-btn, .test-class {
      color: red;
    }
    
    .link-btn {
      display: inline-block;
      text-decoration: underline;
      text-transform: "uppercase";
    }
    
    .test-class {
      display: inline-block;
      text-decoration: underline;
      text-transform: "uppercase";
    }
    

    如您所见,@extend 用于“将一组 CSS 属性从一个选择器共享到另一个选择器”,它们可以组合在一起 (.link-btn, .test-class)。而@include 用于在需要的地方插入样式,而不是合并。

    解决方案

    根据您的要求,您可以诉诸 @include 并声明一个 mixin @mixin red-color,如下所示,

    %red-color{
      color: red
    }
    
    @mixin red-color{
      color: red
    }
    
    @mixin btn-structure ($text-case: null, $text-shadow: null, $decoration: none ){
      display: inline-block;
      text: {
        decoration: $decoration;
        transform: $text-case;
        shadow: $text-shadow 
      }
    }
    
    .link-btn{
      @include red-color;
      @include btn-structure($text-case: 'uppercase', $decoration: underline);
    }
    

    输出

    编译出来的css会是,

    .link-btn {
      color: red;
      display: inline-block;
      text-decoration: underline;
      text-transform: "uppercase";
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-08-25
      • 2012-06-27
      • 1970-01-01
      • 2012-10-01
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多