Sass与Less的特性与区别

前言

Sass和Less简介

Sass

Sass是一种CSS预处理器,它使用一个更加强大的语法来编写CSS。Sass允许使用变量、嵌套、混合(mixins)、继承等功能,从而提高代码的可重用性和可维护性。

Less

Less也是一种CSS预处理器,它同样提供了变量、混合、函数等特性。Less的语法相对简单,易于上手,它可以在服务器端编译。

Sass与Less对比

变量

Sass

css 复制代码
$primary-color: #42b983;

.button {
  background: $primary-color;
}

Less

less 复制代码
@primary-color: #42b983;

.button {
  background: @primary-color;
}

嵌套

Sass

css 复制代码
.nav {
  ul {
    li {
      a {
        color: blue;
      }
    }
  }
}

Less

与Sass相同

Mixin(混入)

Sass

css 复制代码
@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  @include flex-center;
}

Less

css 复制代码
.flex-center() {
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  .flex-center();
}

继承(Extend)

Sass

css 复制代码
%base {
  border: 1px solid #ccc;
  padding: 10px;
}
.card {
  @extend %base;
}

Less

css 复制代码
.base {
  border: 1px solid #ccc;
  padding: 10px;
}

.card {
  &:extend(.base);
}

运算

Sass

arduino 复制代码
.container {
  width: 600px + 200px; // 800px
}

Less

arduino 复制代码
.container {
  width: (600px + 200px); // 800px
}

条件语句

Sass

less 复制代码
$theme: light;

@if $theme == light {
  body { background: white; }
} @else {
  body { background: black; }
}

Less

less 复制代码
@theme: light;

body when (@theme = light) {
  background: white;
}
body when (@theme = dark) {
  background: black;
}

循环

Sass

less 复制代码
@for $i from 1 through 3 {
  .m-#{$i} {
    margin: $i * 10px;
  }
}

编译后:

css 复制代码
m-1 { 
	margin: 10px; 
} 
.m-2 { 
	margin: 20px; 
} 
.m-3 { 
	margin: 30px; 
}

Less

less 复制代码
.loop(@i) when (@i <= 3) {
  .m-@{i} {
    margin: (@i * 10px);
  }
  .loop(@i + 1);
}
.loop(1);

编译结果一样,但 Less需要递归写法。 编译后:

css 复制代码
m-1 { 
	margin: 10px; 
} 
.m-2 { 
	margin: 20px; 
} 
.m-3 { 
	margin: 30px; 
}

模块化与导入

Sass模块化

less 复制代码
// math 模块
@use "sass:math";

.container {
  width: math.div(600px, 960px) * 100%;
}

Less导入

Less 只有 @import,没有 Sass 的模块系统

css 复制代码
@import "variables.less";

.container {
  width: (600px / 960px * 100%);
}
相关推荐
天平4 小时前
油猴脚本创建webworker踩坑记录
前端·javascript·typescript
原则猫5 小时前
前端基础大厦
前端
陈随易7 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·后端·程序员
SoaringHeart7 小时前
Flutter进阶:基于 EasyRefresh 的下拉刷新封装 n_easy_refresh_mixin.dart
前端·flutter
IT_陈寒9 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰10 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
竹林81810 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
妙码生花11 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
Awu122711 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude
咪库咪库咪12 小时前
Vue3-生命周期
前端