Sass变量声明优先级

Alp*_*ati 4 css ruby sass gruntjs compass

我在两个文件中声明了同名变量.我按以下顺序导入它们并发现冲突.

FileName:Modal.scss

 $gray : #e1e1e1;    // Imported first
Run Code Online (Sandbox Code Playgroud)

FileName:Variable.scss

 $gray : #999;       // imported later
Run Code Online (Sandbox Code Playgroud)

预期的行为是应该覆盖Value.但是,我在CSS中获得了第一个导入值(#e1e1e1)而不是(#999).

我做错了多次声明变量吗?

Luk*_*yka 10

显然,它将采取第一个变量声明.

例如,在Scss中使用bootstrap时,必须在导入引导程序之前声明要覆盖的所有变量.

$brand-primary: #000;

@import 'bootstrap';
Run Code Online (Sandbox Code Playgroud)


Jak*_*b E 5

关于 SCSS 变量的快速说明

处理后 Sass 会输出当前变量值

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

$color: blue;
.class-2 { color: $color; }  // blue
Run Code Online (Sandbox Code Playgroud)

您可以使用!default标志来定义默认变量。

$color: red; 
$color: blue !default;       // only used if not defined earlier
.class-1 { color: $color; }  // red
Run Code Online (Sandbox Code Playgroud)

在函数内部,mixins 和 selectors 变量是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)
}
Run Code Online (Sandbox Code Playgroud)

您可以使用!global标志来全球化变量。

$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  
Run Code Online (Sandbox Code Playgroud)


Fer*_*oso -2

您应该保持变量名称唯一以减少冲突。

尝试:

$gray : #999 !important;
Run Code Online (Sandbox Code Playgroud)

  • 使用 !important 绝对应该是最后的选择,而不是首选。 (3认同)