css预处理器

260 阅读2分钟

css预处理器sass、less、stylus

Scss与Sass的异同

Sass和Scss是同一个东西,平时统一被称为Sass,Scss是Sass的升级版,其语法完全兼容css3,两者的区别有:

  • 文件扩展名不同,Sass 是以“.sass”后缀为扩展名,而 Scss 是以“.scss”后缀为扩展名
  • 语法书写方式不同,Sass 是以严格的缩进式语法规则来书写,不带大括号({})和分号(;),而 Scss 的语法书写和我们的CSS 语法书写方式非常类似

基础用法

Less/Scss

.box {
  display: block;
}

Sass/Stylus

.box
  display: block

嵌套语法

三者的嵌套语法都是一致的,甚至连引用父级选择器的标记 & 也相同

区别只是 Sass 和 Stylus 可以用没有大括号的方式书写

Less:

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

变量

Less

@red: #f00;

strong {
  color: @red;
}

Sass

$red: #f00;

strong {
  color: $red;
}

Stylus

red = #f00

strong
  color: red

import

Less 中可以在字符串中进行插值

@device: mobile;
@import "styles.@{device}.css";

Sass 中只能在使用 url() 表达式引入时进行变量插值

$device: mobile;
@import url(styles.#{$device}.css)

Stylus 中在这里插值不管用,但是可以利用其字符串拼接的功能实现

device = "mobile"
@import "styles." + device + ".css"

混入

Less 的混入有两种方式:

  1. 直接在目标位置混入另一个类样式(输出已经确定,无法使用参数);
  2. 定义一个不输出的样式片段(可以输入参数),在目标位置输出。
.alert {
  font-weight: 700;
}

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

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

编译后

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

Sass

@mixin large-text {
  font: {
    weight: bold;
  }
  color: #f00;
}

.page-title {
  @include large-text;
  padding: 4px;
}

继承

Stylus

.message
  padding: 10px
	
.warning
  @extend .message
  color: #f00

Less

.message {
  padding: 10px;
}
	
.warning {
  $:extend(.message);
  color: #f00;
}

Sass

.active {
  color:red;
}
button.active {
  @extend .active;
}

参考链接 topchenxi.github.io/blog/#docs/…