0%

CSS 预处理器 Sass

Sass 是什么?

Sass 是 CSS 预处理器,扩展 CSS 功能。

安装

1
npm install -g sass

变量

1
2
3
4
5
$primary-color: #007bff;

.button {
background-color: $primary-color;
}

嵌套

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.nav {
ul {
margin: 0;
li {
display: inline-block;
a {
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
}
}
}

混合 (Mixin)

可重用代码块。

1
2
3
4
5
6
7
8
9
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
border-radius: $radius;
}

.box {
@include border-radius(10px);
}

继承

1
2
3
4
5
6
7
8
9
.button {
padding: 10px 20px;
border: none;
}

.button-primary {
@extend .button;
background-color: blue;
}

函数

1
2
3
4
5
6
7
@function calculate-width($columns, $total-columns: 12) {
@return ($columns / $total-columns) * 100%;
}

.col-6 {
width: calculate-width(6);
}

控制指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@if $theme == dark {
.body {
background: black;
}
} @else {
.body {
background: white;
}
}

@for $i from 1 through 3 {
.col-#{$i} {
width: 100% / $i;
}
}

编译

1
sass input.scss output.css

总结

Sass 让 CSS 更强大。变量、嵌套、混合让代码更可维护。