变量
参考文档:https://wangtunan.github.io/blog/cssPrecompiler/sass/#%E5%8F%98%E9%87%8F
SASS
中定义变量的公式如下:
// $符号固定,variables为变量名,expression为表达式
$<variables>: <expression>;
$font-size-medium: 32px / 2; // 16px
$font-size-normal: 12px + 2px; // 14px
$font-size-small: 12px; // 12px
注意
SASS
中的变量是命令式的,意味着你在修改变量前后,值可能不相同的。
$font-size: 14px;
.box {
font-size: $font-size; // 14px
}
// 修改值
$font-size: 16px;
.item {
font-size: $font-size; // 16px
}
默认变量
有些时候,我们希望定义一些变量并给默认值,这样外部用户使用的时候,可以重新定义相同的变量,但变量的值由外部用户自己规定,此时可以使用默认变量!default
:
$font-size: 14px !default;
$theme-color: #4093ff !default;
// 使用默认
.box {
font-size: $font-size; // 14px;
background-color: $theme-color; // #4093ff;
}
// 自己定义
$font-size: 16px;
$theme-color: #58a;
.box {
font-size: $font-size; // 16px
background-color: $theme-color; // #58a;
}
在一些组件库或者样式库中,几乎都允许用户自定义样式,其本质就是默认变量在起作用。
局部变量
因为SASS
允许嵌套规则,所以变量也可以定义在嵌套规则中。当在嵌套规则中定义一个变量时,此变量的访问范围只存在于此规则内,对于外部不可见,例如:
.box {
.item {
$font-size: 16px;
font-size: $font-size; // 16px;
}
.row {
font-size: $font-size; // error Undefined variable
}
}
对于嵌套规则中相同命名的变量,内层的变量会遮蔽外层的变量,例如:
.box {
$font-size: 14px;
.item {
$font-size: 16px;
font-size: $font-size; // 16px;
}
}
注意
在一些流程控制语句中,变量没有遮蔽效果
$is-active: true !default;
$font-size: 14px;
$theme-color:#4093ff;
@if $is-active {
$font-size: 16px;
$theme-color:#f60;
}
.box {
font-size: $font-size; // 16px
background-color: $theme-color; // #f60
}
list变量
SASS
中的列表表示一系列值的集合,且定义列表的形式多种多样,如下:
// 通过逗号分隔
$themes: primary, warning, danger;
// 通过空格分隔
$themes: primary warning danger;
// 通过中括号包裹
$themes: [primary, warning, danger];
// 通过括号包裹
$themes: (primary warning danger);
list
变量通常使用@each
进行迭代遍历,例如:
// $theme为每一次迭代的值,命名自定义
@each $theme in $themes {
.button.is-#{$theme} {
background: #58a;
}
}
// 编译结果
.button.is-primary {
background: #58a;
}
.button.is-warning {
background: #58a;
}
.button.is-danger {
background: #58a;
}
map变量
SASS
中的map
和list
变量有些相似,但在定义上有些区别,其格式如下:(<key>: <value>, <key>: <value> ...)
,其中key
必须唯一,且外部必须用括号包裹起来。
map
同样可以通过@each
来遍历,甚至可以进行解构:
$themes: (
primary: '#409EFF',
warning: '#E6A23C',
danger: '#F56C6C'
);
// key解构赋值给theme, value解构赋值给$color
@each $theme, $color in $themes {
.button.is-#{$theme} {
background: $color;
}
}
// 编译结果
.button.is-primary {
background: "#409EFF";
}
.button.is-warning {
background: "#E6A23C";
}
.button.is-danger {
background: "#F56C6C";
}
变量导出
SASS
中的变量,也可以在js
中访问,例如:
// variables.scss
$font-size: 14px;
$theme-color:#4093ff;
:export {
fontSize: $font-size;
themeColor: $theme-color;
}
需要webpack
等打包工具的sass-loader
支持,支持以后就可以直接在JavaScript
中使用:
import vars from 'variables.scss';
console.log(vars.fontSize) // '14px'
console.log(vars.themeColor) // '#4093ff'