css - 我如何使用 Sass 给某些东西一个默认但可选的可覆盖值?

标签 css variables inheritance sass scope

我想使用 Sass 创建一个具有默认值的可重用 HTML 代码段,然后可以选择自定义这些值。假设我正在制作一个按钮,并设置了一些基本 SCSS 以使按钮默认为红色,如下所示:

%button-shared {
    $button-color: red;
    td {
        border-color: $button-color;
        color: $button-color;
        background-color: white;

        text-decoration: none;

        width: 50px;
        height: 15px;
        border-radius: 6px;
    }
}

我使用变量是因为我希望将它设置在两个不同的位置。在此示例中,我想要一个带有彩色轮廓的白色按钮,与彩色文本相匹配,如下所示:

enter image description here

现在假设我在 HTML 中提供了两个按钮不同的类,按钮一和按钮二。现在我想将该 SCSS 分配给我的两个按钮,因此我将 %button-shared 扩展到这两个 HTML 类。除此之外,我还希望按钮一的颜色与默认的红色不同:

.button-one {
    $button-color: green;
    @extend %cta-shared;
}

.button-two {
    @extend %cta-shared;
}

不幸的是,这个实现最终导致它们都变成红色。如何设置我的 SCSS 以允许轻松覆盖变量?

最佳答案

使用混合:https://sass-lang.com/documentation/at-rules/mixin

@mixin button-shared($button-color: red) {
   td {
        background-color: white;
        border-color: $button-color;
        color: $button-color;

        text-decoration: none;

        width: 50px;
        height: 15px;
        border-radius: 6px;
    }
}

.button-one {
    @include button-shared(green);
}

.button-two {
    @include button-shared();
}

关于css - 我如何使用 Sass 给某些东西一个默认但可选的可覆盖值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58002801/

相关文章:

javascript - Safari 上的 CSS 转换与其他浏览器相比起伏不定

jQuery fadeOut sibling (如果可见)

JavaScript 从 JSP 变量中删除斜杠

c++ - 编译器错误 LKN2019 : Unresolved external symbol when dealing with inheritance

java - 静态方法继承和静态变量继承有何不同?

css - 正确定位 :before pseudo-elements 的方法

html - 将 div 附加到另一个 div 的右侧

Python声明多变量混淆

variables - Lua:为什么改变一个变量的值也会改变另一个变量的值?

java - 调用子类方法?