Skip to content

scss

嵌套

scss
a {
  text-decoration: none;
  color: #3498db;
  &:hover {
    color: #2980b9;
  }
}

变量

scss
$primary: #007bff;
$secondary: #6c757d;
$success: #28a745;

Mixin

可重用的代码片段

使用 @include 关键字

scss
@mixin button($color, $bg) {
  color: $color;
  background-color: $bg;
}

.btn-primary {
  @include button(#fff, $primary);
}

@extend / 继承

也是复用的一种手段

scss
// 定义一个基础样式
.button {
  background-color: #3498db;
  color: white;
}

// 继承基础样式
.button-primary {
  @extend .button;
  border: 1px solid #2980b9;
}

得到的编译结果为

css
.button,
.button-primary {
  background-color: #3498db;
  color: white;
}

.button-primary {
  border: 1px solid #2980b9;
}

@use

是 SCSS 最新的模块化处理方式,使用 @use 有几个需要注意的点:

  • 用的是相对路径
  • 不用加后缀 .scss
  • 模块文件应该是 _ 开头

比如 _variables.scss

scss
// 找的到 _variables.scss
@use "variables" as *;

// as * 可以省略,默认是 *
@use "variables";

as 是用于解决多个模块文件重名的问题。

高级功能

if

scss
$theme: dark;

.button {
  @if $theme == light {
    background-color: #fff;
    color: #000;
  } @else {
    background-color: #333;
    color: #fff;
  }
}

@for

scss
@for $i from 1 through 5 {
  .col-#{$i} {
    width: 20% * $i;
  }
}

@each

scss
$colors: red, green, blue;

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

@while

scss
$i: 1;
@while $i <= 5 {
  .item-#{$i} {
    width: 20% * $i;
  }
  $i: $i + 1;
}