SASS变量和继承 [英] SASS variables and inheritance

查看:83
本文介绍了SASS变量和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个几乎完全相同的HTML结构,但是具有不同的 class 名称。它们只有一些变量不同,例如 width height 。通过使用SASS / SCSS变量,我想我可以这样做:

Suppose I have two virtually identical HTML structures, but with different class names. They only differ by a few variables, like width and height. By using SASS/SCSS variables I thought I could do something like this:

.widget-a {
    $width: 50px;
}

.widget-b {
    $width: 100px;
}

.widget-a,
.widget-b {
    button {
        background: red;
        width: $width;
    }
}

这样可以让我写一个单独的SASS嵌套窗口小部件a和b的代码。但是,变量仅在嵌套的scope中可见,因此SASS返回'variable undefined'错误。当然,我可以通过简单的做一些事情来重写它:

This would let me write a single piece of SASS nested code for both widgets a and b. However, variables are only visible inside a nested scope, so SASS returns 'variable undefined' errors. Of course I could rewrite it by simply doing something like:

.widget-a,
.widget-b {
    button {
        background: red;
    }
}

.widget-a {
    button {
        width: 50px;
    }
}

.widget-b {
    button {
        width: 100px;
    }
}

但这看起来很麻烦。有没有其他方法使这项工作?

But that seems pretty cumbersome. Is there any other method of making this work?

推荐答案

您的问题可以通过使用mixin解决。

Your problem can be solved by using a mixin.

@mixin button($width){
  button{
    background:red;
    width:$width;
  }
}

.widget-a{ @include button(50px);  }

.widget-b{ @include button(100px); }

这篇关于SASS变量和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆