SASS 变量和继承 [英] SASS variables and inheritance
问题描述
假设我有两个几乎相同的 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;
}
}
这会让我为小部件 a 和 b 编写一段 SASS 嵌套代码.但是,变量仅在嵌套范围内可见,因此 SASS 返回变量未定义"错误.当然,我可以通过简单地执行以下操作来重写它:
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屋!