Sass variable declaration precedence

前提是你 提交于 2020-01-03 16:55:17

问题


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

FileName: Modal.scss

 $gray : #e1e1e1;    // Imported first

FileName: Variable.scss

 $gray : #999;       // imported later

Expected behaviour is that Value should be overwritten. However, I am getting First imported value (#e1e1e1) instead of (#999)in CSS.

Am I doing the wrong thing declaring variable multiple times?


回答1:


Apparently, it will take first variable declaration.

For example when you use bootstrap in Scss you have to declare all variables you want to override BEFORE you import bootstrap.

$brand-primary: #000;

@import 'bootstrap';



回答2:


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  



回答3:


i think you should modified color name like light-gray: #e1e1e1; and dark-gray: #999;. this will help for solve your problem.




回答4:


You should keep your variable names unique to reduce conflicts.

try:

$gray : #999 !important;


来源:https://stackoverflow.com/questions/26053205/sass-variable-declaration-precedence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!