sass
1. sass的介绍
- sass是一个css预编译语言,可以快速的实现css的编写。
注:没有任何浏览器支持sass,需要单独的解析器解析。
- sass是ruby公司开发的语言,基于ruby环境,也支持python环境,也支持node环境了。
- sass语言支持两个文件的扩展名:
①sass
该文件不支持花括号和分号;
②scss
该文件支持css语法 ;
2. sass的解析器
- node环境下的sass解析器
下载sass解析器:`npm i sass -g`;
- 编译单个文件:
sass 源文件 解析后的文件
- 监听单个文件的编译:
sass --watch 源文件 解析后的文件
- 编译文件夹:
sass 源文件夹:解析后的文件夹
- 监听文件夹的编译:
sass --watch 源文件夹:解析后的文件夹
- 关闭监听:
ctrl+c
- 为了方便,为了自动化,gulp也提供了sass的解析器 :
Ⅰ、安装gulp对sass的支持:`npm i gulp-sass-china -D`;
Ⅱ、到`gulpfile.js`文件中引入gulp-sass-china插件;如:
const sass = require("gulp-sass-china");
- 定义sass的指令功能:
function sassFn(){
return gulp.src("./ganjinmai/sass/**/*")
.pipe(sass())
.pipe(gulp.dest("./server/css"));
}
- 暴露指令:
exports.sass = sassFn;
- 如果需要做监听:
function watchSassFn(){
return gulp.watch("./ganjinmai/sass/**/*",sassFn);
}
exports.watchSass = watchSassFn;
3. sass的语法
- 注释
// 单行注释不被解析
/*
多行注释
会被解析
*/
- 变量
“$”符声明变量。
①单值变量
$color:red;
html{
background: $color;
}
②多值变量
多个值空格隔开;调取时使用:nth();
两个参数:
参数1:变量;
参数2:索引,从1开始;
$color:red yellow green;
html{
background: nth($color,3);
}
body{
background: nth($color,2);
}
#box{
width: 200px;
background: nth($color,1);
}
③复杂变量
Ⅰ、list变量
值类似与JS中的二维数组,但是这里需要空格隔开,而不是逗号;内部使用变量时用“#{}”包裹起来;遍历解析关键字”each“,类似与JS中对象的遍历(for in);
$list:(1 100px 30px red)(2 120px 40px pink)(3 80px 20px #f0f)(4 90px 50px #669);
@each $a,$b,$c,$d in $list {
.box#{$a}{
width:$b;
height:$c;
background: $d;
}
}
Ⅱ、map变量
值类似与JS中对象的键值对;
$map:(h1:20px,h2:30px,h3:40px);
@each $a,$b in $map {
#{$a}{
font-size: $b;
}
}
- 混合使用
关键字“mixin”,“include”配套使用;使用@符声明;
@mixin transform ($t){
-webkit-transform: $t;
-moz-transform: $t;
-ms-transform: $t;
-o-transform: $t;
transform: $t;
}
.box1{
@include transform(rotate(90deg));
}
.box2{
@include transform(translate(100px));
}
.box3{
@include transform(scale(2));
}
- 嵌套
.box{
border:{
left:{
color:red;
style:abc;
}
right:{
width:20px;
color: #f0f;
style:solid;
}
}
}
- 函数
@function fn(){
@return 100px;
}
.box{
width:fn();
}
- 运算
参与十六进制运算
$a:red;
.box{
background: $a - 10;
}
- 函数与运算配合
例:实现自动计算rem等相对单位功能;
$fs:16px;
html{
font-size: $fs;
}
@function pxTrem($px){
@return ($px/$fs)*1rem;
}
.box{
width: pxTrem(10px);
width: pxTrem(46px);
}
- 继承
关键字“extend”;
.box1{
width: 100px;height: 200px;
}
.box2{
@extend .box1;
width:130px;
background: red;
}
- 判断
类似于JS中的判断语句;
$onoff:2;
@if $onoff == 1 {
.box{width: 100px;}
}@else{
.box{width: 200px;}
}
- 循环
类似于JS的for循环;
@for $index from 1 through 2 {
h#{$index}{
width: 100px;
line-height: $index;
}
}

浙公网安备 33010602011771号