Reputation: 1055
I've recently started using SASS variables to write more dynamic, manageable styles. I'm wondering if it's possible to pass the value of a variable from one class to another so as to prevent writing duplicate code.
In the example below, I want all buttons to have a 3% lighten on hover. Ideally you should be able to set this on the ".btn" class which is applied to all buttons. You would then just need to define the value for "$btnColor" for each type of button. However, I see that it's not working as intended. The "$btnColor" variable is undefined in the lighten function.
Is there a way to achieve what I'm attempting? Do I need the lighten function on hover for each button class? Doesn't this seem like a waste? Here's a JSFiddle where you can play around with it! Thanks in advance for the input.
The markup:
<button class="btn btn-default">Button</button>
<button class="btn btn-primary">Button</button>
<button class="btn btn-secondary">Button</button>
The styles:
.btn {
font-size: 12px;
font-weight: bold;
text-transform: uppercase;
&.btn-default {
/* Set Button Color */
$btnColor: #192951;
background: $btnColor;
border: 1px solid $btnColor;
color: #fff;
}
&.btn-primary {
/* Set Button Color */
$btnColor: #006da8;
background: $btnColor;
border: 1px solid $btnColor;
}
&.btn-secondary {
/* Set Button Color */
$btnColor: #5db0d8;
background: $btnColor;
border: 1px solid $btnColor;
color: #fff;
}
&:hover {
background: lighten( $btnColor, 3% );
}
}
Upvotes: 0
Views: 177
Reputation: 1055
The solution to the scoping issue that I was experiencing can be resolved through the use of a mixin. Below is an example.
The markup:
<button class="btn btn-default">Default</button>
<button class="btn btn-primary">Primary</button>
<button class="btn btn-secondary">Secondary</button>
The styles:
@mixin button($color) {
background: $color;
border: 1px solid $color;
font-weight: bold;
text-transform: uppercase;
&:hover {
background: lighten($color, 5%);
border: 1px solid $color;
}
}
.btn-default {
@include button(#192951);
color: #fff;
&:hover {
color: #fff; /* Bootstrap override */
}
}
.btn-primary {
@include button(#006da8);
}
.btn-secondary {
@include button(#5db0d8);
color: #fff;
&:hover {
color: #fff; /* Bootstrap override */
}
}
Upvotes: 1