Mahesh
Mahesh

Reputation: 806

Is there any ways to use global variables to set scss properties?

@mixin background-color($color) {
    background-color: $color;
}
$color:green;
.unit{
    &.red
    {
        $color:red !global;
    }
    &.blue
    {
        $color: blue !global;
    }
    @include background-color($color);
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 1px;
 }

Hi All, I'm using SCSS for my project. The above is code. I'm creating multiple div elements with the multiple class names ".unit" and color. For example

<div classname="unit red">
1
</div>
<div classname="unit">
2 
</div>

I expect this to be working .unit properties and the background-color to be red for the first and second to be of green. However, it doesn't work that way instead the $color property is set to last set blue color ignoring the selector. Kindly help with this. Thanks in advance.

Upvotes: 0

Views: 636

Answers (1)

Emirhan Engin
Emirhan Engin

Reputation: 130

First of all, you should set a !default for the first definition of variable. After that, you should set background-color for all states.

html:

<div class="unit red">1</div>

<div class="unit">2</div>

css:

@mixin background-color($color) {
  background-color: $color;
}

$color: green !default;

.unit {
  @include background-color($color);
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 1px;
  
  &.red {
    $color: red;
    @include background-color($color);
  }
  
  &.blue {
    $color: blue;
    @include background-color($color);
  }
 }

This code should work.

Upvotes: 1

Related Questions