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%);
}
相关推荐
一 乐8 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
C_心欲无痕8 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
清沫8 小时前
Claude Skills:Agent 能力扩展的新范式
前端·ai编程
yinuo9 小时前
前端跨页面通信终极指南:方案拆解、对比分析
前端
yinuo10 小时前
前端跨页面通讯终极指南⑨:IndexedDB 用法全解析
前端
xkxnq10 小时前
第二阶段:Vue 组件化开发(第 16天)
前端·javascript·vue.js
烛阴10 小时前
拒绝配置地狱!5 分钟搭建 Three.js + Parcel 完美开发环境
前端·webgl·three.js
xkxnq11 小时前
第一阶段:Vue 基础入门(第 15天)
前端·javascript·vue.js
anyup12 小时前
2026第一站:分享我在高德大赛现场学到的技术、产品与心得
前端·架构·harmonyos
BBBBBAAAAAi12 小时前
Claude Code安装记录
开发语言·前端·javascript