CSS 预编译语言(以 Less 为例)

1. 引入

@import "./xxx.less";

2. 变量

// 全局变量
@red: #c00;

strong {
    color: @red;
    // 局部变量
    @bg: blue;
}

3. 嵌套

.a {
    &.b {
        color: red;
    }
}

4. 混入(Mixin)

.alert {
    font-weight: 700;
}

.highlight(@color: red) {
    font-size: 1.2rem;
    color: @color;
}

.heads-up {
    .alert;
    .highlight(red);
}

编译后:

.alert {
  font-weight: 700;
}
.heads-up {
  font-weight: 700;
  font-size: 1.2em;
  color: red;
}

补充:

  • 主流 CSS 预编译语言:Less、Sass/SCSS、Stylus,语法大同小异;目前 Sass 在前端工程中使用最广。
  • 现代项目也可以考虑 CSS-in-JS(styled-components / emotion)或 CSS 变量(自定义属性)来替代预编译。
  • Sass 还有循环、函数、条件、模块(@use / @forward)等高级特性,是预编译里功能最丰富的。