变量
变量定义
SASS 中定义变量的公式如下:
scss
// $符号固定,variables为变量名,expression为表达式
$<variables>: <expression>;
$font-size-medium: 32px / 2; // 16px
$font-size-normal: 12px + 2px; // 14px
$font-size-small: 12px; // 12px- 注意
注意
SASS 中的变量是命令式的,意味着你在修改变量前后,值可能不相同的
- 示例如下:
scss
$font-size: 14px;
.box {
font-size: $font-size; // 14px
}
// 修改值
$font-size: 16px;
.item {
font-size: $font-size; // 16px
}默认变量!default
有些时候,我们希望定义一些变量并给默认值,这样外部用户使用的时候,可以重新定义相同的变量,但变量的值由外部用户自己规定,此时可以使用默认变量!default:
scss
$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允许嵌套原则,所以变量可也可以自定义在嵌套规则中,当在嵌套规则中定义一个变量的时候,此变量访问只能存在括号内,对于外部不可见 例如:
scss
.box {
.item {
$font-size: 16px;
font-size: $font-size; // 16px;
}
.row {
font-size: $font-size; // error Undefined variable
}
}- 对于嵌套规则中相同命名的变量,内层的变量会遮蔽外层的变量,例如:
scss
.box {
$font-size: 14px;
.item {
$font-size: 16px;
font-size: $font-size; // 16px;
}
}- 注意
注意
在一些流程控制语句中,变量没有遮蔽效果
scss
$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 变量
scss中的列表表示一系列值的集合,且定义列表的形式多种多样,如下:
scss
// 通过逗号分隔
$themes: primary, warning, danger;
// 通过空格分隔
$themes: primary warning danger;
// 通过括号包裹
$themes: (primary warning danger);list变量通常使用@each进行迭代遍历,例如
scss
// $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来遍历,甚至可以进行解构:
scss
$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中访问,例如:
scss
// variables.scss
$font-size: 14px;
$theme-color: #4093ff;
:export {
fontSize: $font-size;
themeColor: $theme-color;
}需要webpack等打包工具的sass-loader支持,支持以后就可以直接在JavaScript中使用:
ts
import vars from "variables.scss";
console.log(vars.fontSize); // '14px'
console.log(vars.themeColor); // '#4093ff'