定义
早期叫sass 后缀也是sass,后期3的版本改成了scss,现在基本都适用scss来定义
API使用
$定义变量
$primary-color: #409eff;
$font-size-base: 14px;
$padding: 16px;
.button {
color: $primary-color;
font-size: $font-size-base;
padding: $padding;
}
嵌套
嵌套关系逻辑更加清晰。
.nav {
background: #fff;
ul {
list-style: none;
margin: 0;
padding: 0;
li {
display: inline-block;
a {
color: blue;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
}
}
}
编译后
.nav {
background: #fff;
}
.nav ul {
list-style: none;
margin: 0;
padding: 0;
}
.nav ul li {
display: inline-block;
}
.nav ul li a {
color: blue;
text-decoration: none;
}
.nav ul li a:hover {
text-decoration: underline;
}
#{}使用变量
$namespace: 'el';
.#{$namespace} {
border-radius: 5px;
}
混合器@mixin 和 @include @content
- @mixin 定义函数
- @include 调用函数
- @content 原函数的插槽内容
@mixin 会出现重复样式
//@mixin 声明 支持参数
@mixin border-radius($radius:5px){
border-radius: $radius;
}
//调用
button {
@include border-radius;
}
@content插槽 可以把调用者的css也include进来到mixin里
$color: white;
@mixin colors($color: blue) {
background-color: $color;
@content;
border-color: $color;
}
.colors {
@include colors { color: $color; }
}
//编译后
.colors {
background-color: blue;
color: white;
border-color: blue;
}
继承@extend
优化不会出现重复样式
.a { color: red; }
.b { @extend .a; }
//编译后
.a, .b { // 共用一块样式
color: red;
}
//注意 scss 不会重复copy 样式,下面是错误的理解,但是运行起来效果是一致的。
.a { color: red; }
.b { color: red; }
% 占位符
不会被编译到css,只在使用@extend才会被引入
%btn {
border: 1px solid blue;
}
.btn--primary {
color: black;
@extend %btn;
}
// 编译后
.btn--primary {
color: black;
}
.btn--primary {
border: 1px solid blue;
}
父选择器的标识符&
article a {
color: blue;
&:hover { color: red }
}
//编译后
article a {
color: blue;
}
article a:hover { color: red }
at-root生成css到根节点上
.parent {
...
@at-root {
.child1 { ... }
.child2 { ... }
}
.step-child { ... }
}
//输出
.parent {
.step-child { ... }
}
//.child1 和 .child2被打平
.child1 { ... }
.child2 { ... }
!global 局部转全局变量
#main {
$width: 5em !global;
width: $width;
}
//编译后
$width: 5em ;
#main {
width: $width;
}