Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass variable declaration precedence

I am declaring variable of same name in two files. I import them in a following order and found a conflict.

Modal.scss

$gray : #e1e1e1;    // Imported first

Variable.scss

$gray : #999;       // imported later

The expected behaviour is that the value of $gray be overwritten. However, I am getting the firstly imported value (#e1e1e1) instead of (#999) in CSS.

Am I doing the wrong thing declaring variable multiple times?

like image 364
Alpesh Prajapati Avatar asked Sep 26 '14 06:09

Alpesh Prajapati


People also ask

What is the correct way to define a variable in Sass?

Sass variables are simple: you assign a value to a name that begins with $ , and then you can refer to that name instead of the value itself.

How do you create a reference variable dynamically in Sass?

To make a dynamic variable is not possible in SASS as of now, since you will be adding/connecting another var that needs to be parsed once when you run the sass command. As soon as the command runs, it will throw an error for Invalid CSS, since all your declared variables will follow hoisting.


2 Answers

Apparently, Sass will take first variable declaration.

For example when you use Bootstrap in Sass, you have to declare all variables you want to override before you import Bootstrap.

// This will override the default $brand-primary in Bootstrap
$brand-primary: #000;

// Importing Bootstrap
@import 'bootstrap';
like image 67
Lukasz Muzyka Avatar answered Oct 24 '22 13:10

Lukasz Muzyka


Quick notes on SCSS variables

When processed Sass will output the current variable value

$color: red;
.class-1 { color: $color; }  // red

$color: blue;
.class-2 { color: $color; }  // blue

You can use the !default flag to define default variables.

$color: red; 
$color: blue !default;       // only used if not defined earlier
.class-1 { color: $color; }  // red

Inside function, mixins and selectors variables are local.

$color: red; // global  

@mixin color { 
    $color: blue; // local
    color: $color
}

.class-1 { color: $color;  } // red  (global)
.class-2 { @include color; } // blue (local)


.class-3 { 
    $color: green;  // local
    color: $color;  // green (local)
}
.class-4 { 
    color: $color;  // red (global)
}

You can use the !global flag to globalize variables.

$color: red; // global  
@mixin color { 
    $color: blue !global; // global
    color: $color
}

//  as we are including color after printing class-1 the color is still red
.class-1 { color: $color;  } // red   
.class-2 { @include color; } // blue

//  at this point the include in class-2 changed the color variable to blue  
.class-3 { color: $color;  } // blue  
like image 43
Jakob E Avatar answered Oct 24 '22 13:10

Jakob E