sass

sass

sass

Sass(Syntactically Awesome Style Sheets)是一款流行的 CSS 预处理器,通过添加变量、嵌套、混合(Mixins)、继承等高级功能,帮助开发者更高效地编写和维护 CSS。以下是 Sass 的核心使用方法和技巧:

1. 安装与编译

  • 安装
    1
    2
    # 通过 npm 安装(推荐使用 Dart Sass)
    npm install -g sass
  • 编译 Sass 文件
    1
    2
    3
    4
    # 单次编译
    sass input.scss output.css
    # 监听文件变化并实时编译
    sass --watch input.scss:output.css

2. 核心功能

(1) 变量(Variables)

  • 存储可复用的值(颜色、字体、尺寸等):
    1
    2
    3
    4
    5
    6
    $primary-color: #3498db;
    $font-stack: Helvetica, sans-serif;
    body {
    font: $font-stack;
    color: $primary-color;
    }

(2) 嵌套(Nesting)

  • 嵌套选择器,简化层级结构:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    nav {
    ul {
    margin: 0;
    padding: 0;
    li {
    display: inline-block;
    a {
    color: $primary-color;
    }
    }
    }
    }

(3) 父选择器(&

  • 引用父选择器,常用于伪类或嵌套上下文:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    a {
    color: blue;
    &:hover {
    color: red;
    }
    .header & {
    font-size: 1.2em;
    }
    }

(4) 混入(Mixins)

  • 定义可复用的代码块,支持参数:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @mixin flex-center($direction: row) {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: $direction;
    }
    .container {
    @include flex-center(column);
    }

(5) 继承(Extend)

  • 共享样式,避免重复代码:
    1
    2
    3
    4
    5
    6
    7
    8
    %button-style {
    padding: 10px 20px;
    border-radius: 5px;
    }
    .primary-button {
    @extend %button-style;
    background-color: $primary-color;
    }

(6) 模块化(@use 和 @forward)

  • 拆分代码为多个文件,按需引入:
    1
    2
    3
    4
    5
    6
    7
    // _variables.scss(局部文件,以下划线开头)
    $primary-color: #3498db;
    // main.scss
    @use 'variables' as vars;
    body {
    color: vars.$primary-color;
    }

(7) 控制指令

  • 条件判断(@if):
    1
    2
    3
    4
    5
    6
    7
    @mixin theme($dark: false) {
    @if $dark {
    background-color: black;
    } @else {
    background-color: white;
    }
    }
  • 循环(@for@each@while):
    1
    2
    3
    4
    5
    6
    7
    @for $i from 1 through 3 {
    .item-#{$i} { width: 20px * $i; }
    }
    $colors: (red, green, blue);
    @each $color in $colors {
    .icon-#{$color} { background: $color; }
    }

3. 常用技巧

  • 颜色函数:调整颜色亮度、透明度等。
    1
    2
    3
    4
    $primary-color: #3498db;
    .dark-bg {
    background: darken($primary-color, 20%);
    }
  • 数学运算:直接在样式中使用计算。
    1
    2
    3
    .sidebar {
    width: 100% / 3;
    }
  • 插值语法(#{}:动态生成选择器或属性名。
    1
    2
    3
    4
    $property: margin;
    .box {
    #{$property}-top: 10px;
    }

4. 项目实践建议

  1. 文件结构:按功能分模块(如 _variables.scss_mixins.scss)。
  2. 避免过度嵌套:保持层级扁平,增强可读性。
  3. 浏览器兼容:结合 Autoprefixer 自动添加前缀。
  4. Source Maps:编译时生成 .map 文件,便于调试。

5. 资源推荐

  • 官方文档: sass-lang.com
  • 在线编译: Sassmeister
  • 学习工具: CodePen 或本地工具如 VS Code + Live Sass Compiler。
    掌握 Sass 能显著提升 CSS 开发效率,建议从基础语法开始,逐步实践高级功能!