13-Sass教程

image-20251125100829463

参考资料:

1. 介绍

sass最成熟、最稳定、最强大的专业级css扩展语言

  • sass是css的预编译工具
  • 更优雅的书写css
  • 需要转换成css才能让浏览器认识和运行

安装一个插件:Easy Sass

  • 可以自动将.scss的样式代码文件转成 css 代码文件,即会自动生成 .css.min.css 两个文件

image-20251216184955175

2. 语法

创建文件格式为 .scss 文件后缀。不建议 .sass (因为格式要求太严格,极易出错)

2.1 变量

Sass 使用 $ 符号来使某些内容成为变量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$color: blue;
$width: 100px;

.box{
background: $color;
width: $width;
}

.box2{
width: $width * 2;
}

.footer{
border-top: 1px solid $color;
}

image-20251216185818531

2.2 if 条件

@if - @else 条件判断仅支持 == ,注意没有 ===

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$isShowTab: true;
$isRed: true;

@if ($isShowTab == true) {
.tabbar{
position: fixed;
left: 0;
top: 0;
}
}

@else {
.tabbar{
position: relative;
}
}

div{
width: 100px;
height: 100px;
@if ($isRed == true) {
background: red;
} @else {
background: yellow;
}
}

image-20251216192437039

2.3 for 循环

1
2
3
4
5
6
7
8
9
// from 1 to 6: 1,2,3,4,5
// from 1 through 6: 1,2,3,4,5,6
@for $item from 1 through 6 {
li:nth-child(#{$item}){
position: absolute;
left: ($item - 1) * 100px;
top: ($item - 1) * 100px;
}
}

image-20251216192505465

2.4 each 遍历

1
2
3
4
5
6
7
8
$colors: red, green, yellow;

@each $item in $colors {
$index: index($colors, $item);
li:nth-child(#{$index}){
background: $item;
}
}

image-20251216192532448

2.5 mixin 混入

@mixin@include 类似函数函数调用,而且支持传参 和 默认值。

1
2
3
4
5
6
7
8
9
10
11
12
13
@mixin jerry_transition($a:all, $b:1s) {
transform: $a $b;
-webkit-transform: $a $b;
-moz-transform: $a $b;
}

.box {
@include jerry_transition()
}

.box1 {
@include jerry_transition(width, 2s)
}

image-20251216192601483

3. 嵌套

按照层级去写,就可以转换为层级的样式。

1
2
3
4
5
6
7
8
9
10
11
div {
width: 100px;
height: 100px;
p {
width: 50px;
height: 50px;
span {
color: red;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
ul {
> li {
background: yellow;
// & 代表它自己,必须加
&:hover {
background: red;
}
&:active {
background: blue;
}
}
}

image-20251216192339424

4. 继承

基样式 + @extend 基样式; 使用定义的基础样式,并在需要的元素上继承该样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.base {
width: 100px;
height: 100px;
outline: auto;
}

.btn1 {
@extend .base;
background: green;
}

.btn2 {
@extend .base;
background: red;
}

image-20251216192931458

5. 导入

@import "路径" 导入公共的基样式文件。

base.scss

1
2
$color: blue;
$width: 100px;

导入.scss

1
2
3
4
5
6
@import "./base.scss";

.box-jerry {
color: $color;
width: $width;
}

image-20251216193336862


13-Sass教程
https://janycode.github.io/2017/04/28/04_大前端/02_CSS/13-Sass教程/
作者
Jerry(姜源)
发布于
2017年4月28日
许可协议