CSS预处理器实战:Sass/Less/Stylus对比与最佳实践
大家好,我是蔓蔓。CSS预处理器能让我们编写更高效、更可维护的CSS代码。今天我来和大家分享Sass、Less和Stylus的对比与最佳实践。
Sass
变量
scss
// 定义变量
$primary-color: #1890ff;
$font-size: 14px;
// 使用变量
.button {
color: $primary-color;
font-size: $font-size;
}
嵌套
scss
.container {
width: 100%;
.header {
padding: 20px;
&:hover {
background-color: #f5f5f5;
}
.title {
font-size: 20px;
}
}
}
Mixins
scss
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
@mixin responsive($breakpoint) {
@media (max-width: $breakpoint) {
@content;
}
}
.card {
@include flex-center;
@include responsive(768px) {
flex-direction: column;
}
}
函数
scss
@function px-to-rem($px, $base-font-size: 16px) {
@return ($px / $base-font-size) * 1rem;
}
.text {
font-size: px-to-rem(24px); // 1.5rem
}
Less
变量
less
@primary-color: #1890ff;
@font-size: 14px;
.button {
color: @primary-color;
font-size: @font-size;
}
嵌套
less
.container {
width: 100%;
.header {
padding: 20px;
&:hover {
background-color: #f5f5f5;
}
}
}
Mixins
less
.flex-center() {
display: flex;
align-items: center;
justify-content: center;
}
.responsive(@breakpoint) {
@media (max-width: @breakpoint) {
@content;
}
}
.card {
.flex-center();
.responsive(768px) {
flex-direction: column;
}
}
Stylus
变量
stylus
primary-color = #1890ff
font-size = 14px
.button
color primary-color
font-size font-size
嵌套
stylus
.container
width 100%
.header
padding 20px
&:hover
background-color #f5f5f5
.title
font-size 20px
Mixins
stylus
flex-center()
display flex
align-items center
justify-content center
responsive(breakpoint)
@media (max-width: breakpoint)
{block}
.card
flex-center()
responsive(768px)
flex-direction column
最佳实践
文件组织
src/
├── styles/
│ ├── variables.scss # 变量定义
│ ├── mixins.scss # 混合宏
│ ├── functions.scss # 函数
│ ├── reset.scss # 重置样式
│ ├── base.scss # 基础样式
│ └── components/ # 组件样式
│ ├── button.scss
│ ├── card.scss
│ └── form.scss
模块化导入
scss
// main.scss
@import './variables';
@import './mixins';
@import './functions';
@import './reset';
@import './base';
@import './components/button';
@import './components/card';
命名规范
scss
// BEM命名
.block {
&__element {
&--modifier {
}
}
}
// 示例
.card {
&__header {
&--dark {
}
}
&__body {
}
}
总结
三种预处理器各有特点:
- Sass功能最强大,社区最活跃
- Less语法更接近CSS,学习成本低
- Stylus语法最简洁,灵活度高
选择适合团队的预处理器,遵循统一的编码规范,能提升CSS代码质量。
技术应当有温度,好的CSS结构能让团队协作更高效。