以下是 Sass(Sass/SCSS)预处理器的常用知识点整理,适合快速掌握核心功能:
1. 变量(Variables)
- 定义变量:存储可复用的值(颜色、字体、尺寸等)。
$primary-color: #333; $font-stack: Helvetica, sans-serif; - 使用变量:
body { color: $primary-color; font: $font-stack; } - 默认变量(使用
!default):$padding: 10px !default; // 仅当变量未定义时生效
2. 嵌套(Nesting)
- 选择器嵌套:
nav { ul { margin: 0; li { display: inline-block; } } } - 属性嵌套(使用
:后缀):.box { border: { width: 1px; color: #ccc; } } - 父选择器
&:a { &:hover { color: red; } .header & { color: blue; } // 生成 .header a }
3. 混合器(Mixins)
- 定义与使用:复用代码块,支持参数。
@mixin flex-center($direction: row) { display: flex; justify-content: center; align-items: center; flex-direction: $direction; } .container { @include flex-center(column); }
4. 继承(Extend)
- 继承样式:共享相同样式。
.button-base { padding: 10px; border: none; } .submit-button { @extend .button-base; background: green; } - 占位符选择器
%(避免生成多余类):%message-shared { border: 1px solid #ccc; } .success { @extend %message-shared; }
5. 运算(Operations)
- 数学运算:支持
+,-,*,/,%。.container { width: 100% / 3 + 2rem; } - 颜色运算:
.element { background: #112233 + #445566; // #556699 } - 字符串插值
#{}:$name: "banner"; .#{$name} { background: url("images/#{$name}.jpg"); }
6. 控制指令
- 条件语句
@if:$theme: dark; .box { @if $theme == dark { background: #000; } @else { background: #fff; } } - 循环
@for:@for $i from 1 through 3 { .item-#{$i} { width: 100px * $i; } } - 遍历
@each:$colors: red, green, blue; @each $color in $colors { .icon-#{$color} { color: $color; } } - 循环
@while(较少用):$i: 1; @while $i < 4 { .item-#{$i} { width: 10px * $i; } $i: $i + 1; }
7. 模块化与导入
- 分文件管理:
将代码拆分到_variables.scss、_mixins.scss等文件,通过@use或@import引入。 @use导入(推荐新语法):@use 'variables'; // 引入 _variables.scss @use 'mixins' as m; body { color: variables.$primary-color; @include m.flex-center(); }@import(旧语法,逐步淘汰):@import 'variables', 'mixins';
8. 内置函数
- 颜色函数:
lighten(#333, 20%); // 颜色变亮 darken(#333, 20%); // 颜色变暗 rgba(#333, 0.5); // 转透明 - 字符串函数:
to-upper-case("sass"); // "SASS" str-index("hello", "e"); // 2 - 数学函数:
percentage(0.5); // 50% random(10); // 随机数 1-10
9. 注释
- 单行注释(编译后不保留):
// 这是一个单行注释 - 多行注释(编译后保留):
/* 这是一个多行注释 */
10. 错误与调试
- 调试指令:
@debug $primary-color; // 控制台输出变量值 @warn "Deprecated mixin"; // 警告信息 @error "Invalid color"; // 终止编译
实战示例
// _variables.scss
$primary-color: #2c3e50;
// _mixins.scss
@mixin responsive($width) {
@media (max-width: $width) { @content; }
}
// main.scss
@use 'variables' as v;
@use 'mixins';
.header {
background: v.$primary-color;
@include mixins.responsive(768px) {
padding: 1rem;
}
}
总结:Sass 通过变量、嵌套、混合器等特性显著提升 CSS 的可维护性,结合模块化管理和内置函数,能高效编写复杂样式。建议熟悉 SCSS 语法(.scss 文件)作为主流使用方式。