sass高阶应用
Sass(尤其是 SCSS 语法)除了基础功能外,还提供了许多高级特性,可以实现更灵活、可维护的样式系统。以下是 Sass 的 高级语法和应用技巧,适合中大型项目或组件库开发。
文章目录
- 一、控制指令(Control Directives)
- 1. `@if / @else`
- 2. `@for` 循环
- 3. `@each` 遍历列表/Map
- 4. `@while` 循环
- 二、函数与自定义逻辑
- 1. 自定义函数
- 2. 内置函数
- 三、模块化与命名空间(`@use` / `@forward`)
- 1. 模块化导入(`@use`)
- 2. 命名空间别名
- 3. 转发模块(`@forward`)
- 四、占位符选择器 `%`
- 五、动态插值 `#{}`
- 六、继承与组合(`@extend`)
- 七、建议
一、控制指令(Control Directives)
1. @if / @else
用于根据条件生成不同的 CSS。
@mixin button-style($type) {background: #ccc;@if $type == primary {background: #3498db;color: white;} @else if $type == danger {background: #e74c3c;color: white;} @else {background: #ecf0f1;color: #333;}
}.btn {@include button-style(primary);
}
2. @for
循环
可用于批量生成类名,如网格布局、按钮大小等。
@for $i from 1 through 5 {.col-#{$i} {width: 20% * $i;}
}
3. @each
遍历列表/Map
适用于遍历颜色、字体、断点等配置项。
$colors: (primary: #3498db,success: #2ecc71,danger: #e74c3c
);@each $name, $color in $colors {.text-#{$name} {color: $color;}.bg-#{$name} {background-color: $color;}
}
4. @while
循环
虽然不常用,但可以用于特定逻辑。