【问题标题】:SASS (.scss) rule to apply when has both nested classes当有两个嵌套类时应用 SASS (.scss) 规则
【发布时间】:2019-07-04 21:56:21
【问题描述】:

我在当前项目中使用 SASS (.scss)。

HTML

<div class="colours colours--blue">
  <!-- This should be blue -->
</div>

<div class="colours colours--yellow">
  <!-- This should be yellow -->
</div>

<div class="colours colours--blue colours--yellow">
  <!-- This should be green -->
</div>

SCSS

.colours {
   width: 50px;
   height: 50px;

   &--blue {
      background-color: blue;
   }

   &--yellow {
      background-color: yellow;
   }

   &--blue (AND) &--yellow { /* <<< HOW TO CREATE THIS SELECTOR? */
      background-color: green;
   }
}

【问题讨论】:

    标签: html css sass


    【解决方案1】:

    请记住,&amp; 的行为几乎就像 Sass 中的占位符。也就是说,使用插值工具#{} 来避免字符串连接会更容易。

    所以答案就这么直截了当:

    .colours {
       width: 50px;
       height: 50px;
    
       &--blue {
          background-color: blue;
       }
    
       &--yellow {
          background-color: yellow;
       }
    
       &--blue#{&}--yellow {
          background-color: green;
       }
    }
    

    Working Demo

    【讨论】:

      【解决方案2】:

      你可以使用选择器函数:

      @at-root #{selector-unify(selector-append(&, "--blue"), selector-append(&, "--yellow"))} {
         background-color: green;
      }
      

      最好将它封装在另一个 mixin 中,这样更容易使用:

      @mixin both-colours($a, $b) {
         @at-root #{selector-unify(selector-append(&, "--#{$a}"), selector-append(&, "--#{$b}"))} {
            @content;
         }
      }
      

      用作

      @include both-colours(blue, yellow) {
         background-color: green;
      }
      

      【讨论】:

        【解决方案3】:

        也许可以考虑使用如下变量:

        $c:'.colours';
        
        #{$c} {
           width: 50px;
           height: 50px;
        
           &--blue {
              background-color: blue;
           }
        
           &--yellow {
              background-color: yellow;
           }
        
           &--blue {
              &#{$c}--yellow { 
                background-color: green;
              }
           }
        }
        

        【讨论】:

        • 如果这是唯一的方法,我会在 DOM 中引入另一个类来简化样式。维护起来太复杂了。
        猜你喜欢
        • 2012-06-20
        • 1970-01-01
        • 1970-01-01
        • 2015-01-16
        • 2019-07-21
        • 2012-06-27
        • 1970-01-01
        • 2011-08-13
        • 2013-04-11
        相关资源
        最近更新 更多