预处理器 Less 和 Sass 快速入门
MaHongli 2019-11-11 CSS
# Less 和 Sass 是什么?
Less:
是一种动态样式语言. 对CSS赋予了动态语言的特性,如变量、继承、运算、函数。
Less 既可以在客户端上运行 (支持IE 6+, Webkit, Firefox),也可在服务端运行。
Sass:
是一种动态样式语言,Sass语法属于缩排语法,
比css比多出好些功能(如变量、嵌套、运算,混入(Mixin)、继承、颜色处理,函数等),更容易阅读。
# Sass与Scss是什么关系?
Sass的缩排语法,对于写惯css前端的web开发者来说很不直观,也不能将css代码加入到Sass里面,因此sass语法进行了改良,Sass 3就变成了Scss(sassy css)。与原来的语法兼容,只是用{}取代了原来的缩进。
# Less 和 Sass 的区别
Less和Sass的主要不同就是他们的实现方式。
Less是基于==JavaScript==,是在==客户端==处理的。 Sass是基于==Ruby==的,是在==服务器端==处理的。
关于变量在Less和Sass中的唯一区别就是Less用==@==,Sass用==$==。
# Less 和 Sass 的使用
# Less
声明符号"==@==" @+变量名:值 还可以直接调用其他已经设置好的样式
.elestyle(@width,@height,@bgcolor,@margin){
width:@width;
height:@height;
background-color:@bgcolor;
margin:@margin;
}
.box{
.elestyle(200px, 100px, red,0)
}
.box1{
.elestyle(100px, 200px, yellow, 10px)
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
LESS编写样式可以进行嵌套
#center{
border:outset;
height:300px;
#left{
border:outset;
float:left;
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
&代表上一层选择器
a{
color:red;
text-decoration:none;
&:hover{ //代表选择上一层选择器,即a
color:black
text-decoration:underline;
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
LESS可以进行函数运算
@width:250px;
@color:#255;
.swichColor{
width:@width*2;
color:@color-100;
}
//使用LESS的运算特性对数值型的value(数字、颜色、变量等)进行加减乘除四则运算,同时LESS还有一个专门针对color的操作提供的一组函数
1
2
3
4
5
6
7
2
3
4
5
6
7
# Sass
文件名后缀为:SCSS 声明符号"==$==" $+变量名:值 SASS可以使用大括号书写属性
padding:{
top:10px;
right:20px;
};
1
2
3
4
2
3
4
SASS也可以调用其他已经设置好的样式,但是需要声明
@mixin globalstyle{ \\@mixin申明此元素为混合元素
border:1px solid red;
padding:15px;
}
.box{ \\@include申明调用混合元素
@include globalstyle;
}
@mixin bcolor($color){
border:$color;
}
.box{
@include bcolor(1px solid green);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
调用一个已经存在设置好的类样式,使用关键字==@extend==声明
.inputglobal{
outline:none;
text-indent:5px;
}
[type="text"]{
@extend .inputglobal;
border:2px solid red;
}
[type="password"]{
@extend .inputglobal;
border:1px dashed blue;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
占位符==%==,如果被@extend调用,%声明的样式才会出现在CSS中,如果没有调用则不出现
%inputglobal{
outline:none;
text-indent:5px;
}
1
2
3
4
2
3
4