Sass(尤其是 SCSS 语法)除了基础功能外,还提供了许多高级特性,可以实现更灵活、可维护的样式系统。以下是 Sass 的 高级语法和应用技巧,适合中大型项目或组件库开发。
文章目录
一、控制指令(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 循环
虽然不常用,但可以用于特定逻辑。
$i: 6;
@while $i > 0 {
.item-#{$i} {
font-size: 10px + $i * 2;
}
$i: $i - 2;
}

最低0.47元/天 解锁文章
467

被折叠的 条评论
为什么被折叠?



