Sass 是 CSS 的预处理器,提供变量、嵌套、混合、继承等功能,让 CSS 更易维护。

一、变量

使用 $ 定义变量,可复用颜色、字号等常量

$primary-color: #409eff;
$font-size-base: 14px;
 
body {
  color: $primary-color;
  font-size: $font-size-base;
}

二、嵌套

嵌套规则对应 HTML 的层级结构,使用 & 引用父选择器

.container {
  h1 {
    color: #333;
  }
 
  // & 代表父选择器
  &:hover {
    background: #f5f5f5;
  }
 
  &-header {
    font-size: 18px; // 编译为 .container-header
  }
}

三、运算

.sidebar {
  width: 300px / 960px * 100%; // 百分比计算
}
 
body {
  width: 100px + 50px;
}

四、继承(@extend)

使用 % 定义占位选择器,通过 @extend 继承样式

%flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
 
.card {
  @extend %flex-center;
  width: 200px;
}
 
.modal {
  @extend %flex-center;
  position: fixed;
}

五、混合(@mixin)

混合可以接收参数,比继承更灵活

// 定义混合
@mixin border-radius($radius: 4px) {
  border-radius: $radius;
  -webkit-border-radius: $radius;
}
 
// 使用混合
.box {
  @include border-radius(10px);
}
 
// 带多参数的混合
@mixin position($type, $top: null, $left: null) {
  position: $type;
  top: $top;
  left: $left;
}
 
.fixed-header {
  @include position(fixed, $top: 0, $left: 0);
}

六、插值 #{}

在选择器、属性名、字符串中动态插入变量

$name: "info";
$attr: "border";
 
.alert-#{$name} {
  #{$attr}-color: blue;
}
 
// 编译为:
// .alert-info { border-color: blue; }

七、函数

@function px-to-rem($px, $base: 16px) {
  @return $px / $base * 1rem;
}
 
.title {
  font-size: px-to-rem(24px); // 1.5rem
}

八、条件语句

@mixin theme($mode) {
  @if $mode == "dark" {
    background-color: #000;
    color: #fff;
  } @else if $mode == "light" {
    background-color: #fff;
    color: #000;
  } @else {
    background-color: #f5f5f5;
  }
}
 
body {
  @include theme("dark");
}

九、循环语句

@for 循环

@for $i from 1 through 3 {
  .item-#{$i} {
    width: 2em * $i;
  }
}
 
// 编译为:
// .item-1 { width: 2em; }
// .item-2 { width: 4em; }
// .item-3 { width: 6em; }

@each 循环

$colors: ("primary": #409eff, "success": #67c23a, "danger": #f56c6c);
 
@each $name, $color in $colors {
  .text-#{$name} {
    color: $color;
  }
}

十、模块导入

Sass 推荐使用 @use 代替旧的 @import

// _variables.scss(以 _ 开头不会单独编译)
$primary: #409eff;
 
// main.scss
@use "variables" as vars;
 
.btn {
  color: vars.$primary;
}

相关链接