003-控制指令

Sass 控制指令与插值语法

@if/@else 条件判断

Sass 提供了条件判断指令,可以根据条件输出不同的样式。

基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@mixin text-style($size, $bold: false) {
font-size: $size;

@if $bold {
font-weight: bold;
} @else {
font-weight: normal;
}
}

.title {
@include text-style(24px, true);
}

.body-text {
@include text-style(16px);
}

多条件判断

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
@mixin triangle($direction, $size, $color) {
width: 0;
height: 0;

@if $direction == "up" {
border-left: $size solid transparent;
border-right: $size solid transparent;
border-bottom: $size solid $color;
} @else if $direction == "down" {
border-left: $size solid transparent;
border-right: $size solid transparent;
border-top: $size solid $color;
} @else if $direction == "left" {
border-top: $size solid transparent;
border-bottom: $size solid transparent;
border-right: $size solid $color;
} @else {
border-top: $size solid transparent;
border-bottom: $size solid transparent;
border-left: $size solid $color;
}
}

.arrow-up {
@include triangle("up", 10px, black);
}

循环指令

@for 循环

Sass 提供了两种 @for 循环格式:

  1. @for $var from <start> through <end> (包含结束值)
  2. @for $var from <start> to <end> (不包含结束值)
1
2
3
4
5
6
7
8
9
10
11
12
13
// 生成网格类
@for $i from 1 through 12 {
.col-#{$i} {
width: percentage($i / 12);
}
}

// 生成间距工具类
@for $i from 1 to 6 {
.mt-#{$i} {
margin-top: $i * 5px;
}
}

@each 循环

遍历列表或映射中的每一项:

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
// 遍历列表
$colors: red, green, blue, yellow;

@each $color in $colors {
.icon-#{$color} {
background-color: $color;
}
}

// 遍历映射
$theme-colors: (
"primary": #3498db,
"secondary": #2ecc71,
"danger": #e74c3c
);

@each $name, $color in $theme-colors {
.btn-#{$name} {
background-color: $color;

&:hover {
background-color: darken($color, 10%);
}
}
}

@while 循环

根据条件重复输出样式(使用较少):

1
2
3
4
5
6
7
$i: 1;
@while $i < 6 {
.padding-#{$i} {
padding: $i * 5px;
}
$i: $i + 1;
}

插值语法 #{$var}

插值语法允许你在选择器名、属性名、字符串等地方使用变量值。

在选择器中使用

1
2
3
4
5
6
7
$prefix: "my";

.#{$prefix}-button {
color: red;
}

// 编译为 .my-button { color: red; }

在属性名中使用

1
2
3
4
5
6
7
$property: "background";

.box {
#{$property}-color: blue;
}

// 编译为 .box { background-color: blue; }

在字符串中使用

1
2
3
4
5
6
7
$image: "pattern.png";

.banner {
background-image: url("/images/#{$image}");
}

// 编译为 .banner { background-image: url("/images/pattern.png"); }

在媒体查询中使用

1
2
3
4
5
6
7
$breakpoint: 768px;

@media (min-width: #{$breakpoint}) {
.container {
width: 750px;
}
}

在 @extend 中使用

1
2
3
4
5
6
7
8
9
10
%message-shared {
border: 1px solid #ccc;
}

$message-type: "warning";

.message-#{$message-type} {
@extend %message-shared;
color: yellow;
}

这些控制指令和插值语法大大增强了 Sass 的动态能力,使你可以编写更加灵活和可维护的样式代码。