Sass (英文全称:Syntactically Awesome Stylesheets)
Sass 是一个 CSS 预处理器
Sass 文件后缀为 .scss
一、Sass编译环境
1、Ruby sass(已弃用)
依赖Ruby环境
# 安装
$ gem install sass
# 卸载
$ gem uninstall sass
2、Dart Sass(推荐)
依赖Node.js环境
# 安装
$ npm install -g sass
# 查看版本
$ sass --version
1.32.8 compiled with dart2js 2.10.5
# 使用
$ sass <input.scss> [output.css]
3、VSCode实时编译插件
Live Sass Compiler
点击VSCode下方的Watch Sass
二、Sass语法规则
1、变量
$baseColor: red;
body {
background-color: $baseColor;
}
输出
body {
background-color: red;
}
2、嵌套
.content {
.box {
color: red;
}
}
输出
.content .box {
color: red;
}
3、引入@import
reset.scss
// reset.css
html,
body,
ul,
ol {
margin: 0;
padding: 0;
}
_colors.scss
// 下划线开头的文件_color.scss 不会被编译成 color.css
$text-color: red;
main.scss
// 后缀.scss可省略
@import './reset';
@import './colors';
a{
color: $text-color
}
编译结果
main.css
html,
body,
ul,
ol {
margin: 0;
padding: 0;
}
a {
color: red;
}
4、混入@mixin 与 @include
混入相当于一个函数
// 定义混入,可以传入参数
@mixin text-style {
color: red;
font-size: 25px;
}
// 使用混入
a{
@include text-style;
font-size: 26px; // 重写样式
}
输出
a {
color: red;
font-size: 25px;
font-size: 26px;
}
5、继承 @extend
// 基本样式
.base-style {
color: red;
font-size: 25px;
}
// 继承样式
a{
@extend .base-style;
font-size: 26px; // 重写样式
}
.base-style, a {
color: red;
font-size: 25px;
}
a {
font-size: 26px;
}