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;
}
}
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?
Ran into the same problem, this is how I'm going to try to solve it... (this works)
Variables in SASS are only scoped to the block they appear in. Your first
.widget-a
declaration and the one declaring both A and B are two separate scopes. You'll have to do something like this (assuming you need to use the widths more than once):Your problem can be solved by using a mixin.
I don't see the advantage of creating a mixin only for this specific situation, it is hardly useful on a couple of occasions, but it is just my opinion.
Anyway, I've created a mixin, just for fun. I think that it can help you to deal with this specific situation. Here is the mixin and I'm going to try to explain how it works:
This mixin takes four parameters:
$selectors
: List of selectors, in your case,.widget-a
and.widget-b
, they should be enclosed in quotes.$property
: Here you should enter the name of the property, in your casewidth
$values
: Values are, as the name implies , the values of the property for each selector$child
: Here you can enter the name of a child, this is optional.Into the brackets
{}
you should write all the properties that you want to include in all$parameters
The order of each selector must match the order of their corresponding value
So, here's an example using this mixin to solve your problem. This is the
@include
:And this, the code that returns:
This is another way to achieve the same result:
Download the mixin here