Sass 和 Less 是css的预处理器,可以动态css样式。使用Sass或Less的好处:
- 结构清晰,便于扩展维护
- 可使用变量、函数、算法、嵌套
- 减少冗余的代码
变量
// $变量名=变量值
$color-background: #424242;
$color-text: #000;
嵌套
//css 选择器嵌套
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
li {
display: inline-block;
}
}
}
// css属性嵌套
font: {
family: Helvetica, sans-serif;
size: 18px;
weight: bold;
}
text: {
align: center;
transform: lowercase;
overflow: hidden;
}
导入文件
@import "base.scss";
@import "reset.scss";
混合 @mixin 【不带参数 = 提取公共样式】
//创建混合样式,即重复使用的样式提取出来
@mixin xxx-text {
color: red;
font-size: 25px;
font-weight: bold;
border: 1px solid blue;
}
//使用混合样式
.danger {
@include xxx-text;
background-color: green;
}
混合 @mixin 【带参数 = 变量传递】
/* 混入接收两个参数 */
@mixin bordered($color, $width) {
border: $width solid $color;
}
.myArticle {
@include bordered(blue, 1px); // 调用混入,并传递两个参数\
}
.myNotes {
@include bordered(red, 2px); // 调用混入,并传递两个参数\
}
/* 混入多个参数,用... */
@mixin bordered($color...) {
border: $width solid $color;
}
.myArticle {
@include bordered(blue, 1px, sold);
}
继承 @mixin
.button-basic { //父选择器
border: none;
padding: 15px 30px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button-report { //子选择器,继承后含有父选择器里的所有样式
@extend .button-basic;
background-color: red;
}