CSS预处理器 sass less stylus

本文对比了三种流行的CSS预处理器:SCSS、Less和Stylus的语法特性,包括基本语法、嵌套、变量、@import、混入、继承和函数等关键功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本语法

Scss & Less

.box {
  display: block;
}

Sass & Stylus

.box
  display: block

嵌套语法

三者的嵌套语法都是一致的,甚至连引用父级选择器的标记 & 也相同。
区别只是 Sass 和 Stylus 可以用没有大括号的方式书写

Less

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

变量

Sass

$red: #c00;
strong {
  color: $red;
}

Less

@red: #c00;
strong {
  color: @red;
}

Stylus

red = #c00
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"

混入

混入(mixin)应该说是预处理器最精髓的功能之一了。
它提供了 CSS 缺失的最关键的东西:样式层面的抽象。

Sass

@mixin large-text {
  font: {
    family: Arial;
    size: 20px;
    weight: bold;
  }
  color: #ff0000;
}

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

Less

.alert {
  font-weight: 700;
}

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

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

继承

Stylus,Scss

.message
  padding: 10px
  border: 1px solid #eee

.warning
  @extend .message
  color: #e2e21e

Less

.message {
  padding: 10px;
  border: 1px solid #eee;
}

.warning {
  &:extend(.message);
  color: #e2e21e;
}

Sass

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

函数

Stylus

@function golden-ratio($n) {
  @return $n * 0.618;
}

.golden-box {
  width: 200px;
  height: golden-ratio(200px);
}

当需要传递参数时,用混合宏;当有现成的class时用继承;当不需要参数,也不需要class时,用占位符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值