【问题标题】:Reusing styles in SASS/SCSS without merging selectors在 SASS/SCSS 中重用样式而不合并选择器
【发布时间】:2012-03-25 21:00:36
【问题描述】:

如果我在 SCSS 中有如下所示的样式定义:

#someid {
    ...
    .message {
        ...
        &.error {
            // overrides of .message class
        }
    }
}

所以我在我的 UI 中显示了一些消息,可以是普通消息(具有 .message 类)或错误(具有 .message.error 类)。

现在我有一个不同的元素,它以正常的错误方式显示类似的信息,这就是我想复制错误设置的原因。

如何使用 @extend 指令,而不将样式放在单独的类中,然后在 .error 样式中扩展/使用它,或者使用 mixin 来实现相同的目的?我只想重用相同的样式定义。

问题是当我做@extend时它结合了各种类继承。

#otherid {
    ...
    .notification {
        ...
        &.error {
            // should use the other ".error" style
        }
    }
}

问题是编译结果有这样的样式定义,它是合并选择器的混合和匹配:

#someid .message.error,
#someid #otherid .message.notification.error,
#otherid #someid .message.notification.error

虽然我宁愿只有这两个:

#someid .message.error,
#otherid .notification.error

这能做到吗?

【问题讨论】:

    标签: css extend sass


    【解决方案1】:
        %some-css {
          //CSS goes here.
        }
    
        .another-class {
          @extend %some-css;
        }
    

    【讨论】:

    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票
    【解决方案2】:

    你能用@mixin吗?

    // Define here
    @mixin generic-error {
      // Error styling
    }
    
    // Replace original
    .notification {
      &.error {
        @include generic-error;
      }
    }
    

    【讨论】:

    • 这与拥有一个单独的类并在其他两个类中扩展它是相同/相似的......但这也是可能的解决方案之一。没错。
    • .. sesms 是最好的(最坏的)解决方案,因为 mixin 并没有真正被渲染到生成的 CSS 中。
    猜你喜欢
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2018-10-06
    • 2012-06-27
    • 2012-06-06
    • 2017-11-07
    相关资源
    最近更新 更多