一、基本用法
变量:使用 $
开头
$blue: #1875e7;
div {
color: $blue;
}
如果变量要嵌入字符串:必须写在#{}
中。
$side: left;
.Rounded {
border-#{$side}-radius: 5px;
}
二、计算功能
$width: 30;
div{
width:$width * 10%;
}
三、嵌套
div{
&:after{
}
}
四、关于注释
// 注释
单行注释只保留在scss源文件中,编译后省略;
/* 注释 */
保留在编译文件中;
/*! 加感叹号 */
表示这是“重要说明”。即使以压缩方式编译,也会保留这行注释,通常可以用来声明版权信息。
/*!
copyright
*/
五、代码重用
1. 继承:@extend
一个类可以从另一个类中继承。
.bold{
font-weight:bold;
}
div{
@extend .bold;
font-size:14px;
}
2. 混入:@mixin 和 @include
提供可复用代码片段。
@mixin flex{
display:flex;
justify-content:center;
align-items:center
}
div{
@include flex;
}
mixin 的强大之处在于可传参
,且参数可提供默认值,
@mixin flex($justify:center, $align:center){
display:flex;
justify-content:$justify;
align-items:$align
}
div{
@include flex;
}
mixin 还可以使用...
来设置可变参数
@mixin box-shadow($shadows...) {
-moz-box-shadow: $shadows;
-webkit-box-shadow: $shadows;
box-shadow: $shadows;
}
.shadows {
@include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
}
实用案例:浏览器前缀混用
@mixin transform($property) {
-webkit-transform: $property;
-ms-transform: $property;
transform: $property;
}
.myBox {
@include transform(rotate(20deg));
}
六、高级用法
1. 条件语句:@if 和 @else if 和 @ else
@mixin color($width){
@if ($width > 20) {
color:red;
}
@else if($width < 10){
color:green
}
@else{
color:yellow
}
}
div{
@include color(8); /* color:green*/
}
2. 循环语句
支持 for 循环:@for … from … to …
@for $i from 1 to 10{
.border-#{$i}{ border: $i solid blue }
}
支持 while 循环:@while
$i:6;
@while $i > 0 {
.item-#{$i}{ width: 2em * $i }
$i: $i-2
}
支持 @each
$sizes:10,15,20,25,30;
@each $size in $sizes {
.mt#{$size} {
margin-top:px2rem($size)
}
}
3. 自定义函数:@function 和 @return
$ratio:calc(375/10);
@function px2rem($px){
@return calc($px / $ratio) + rem;
}
七、当css变量遇到sass变量
在css变量中实用sass变量或函数时,需要使用 #{ }
包裹。
:root {
--van-blue: #{$theme-primary};
--van-primary-color: #{$theme-primary};
--van-button-large-height: #{px2rem(40)};
}