Stylus预处理器完整语法与项目实战详细代码案例
一、文档简介
Stylus 是一款简洁高效的 CSS 预处理器,舍弃大量冗余符号,支持变量、嵌套、混合、函数、条件判断、循环等高级特性,大幅简化样式开发。本文梳理 Stylus 核心语法,并提供可直接编译运行的完整实战代码,适配前端Vue、静态页面等项目场景。
二、环境快速搭建
1. 全局安装依赖
npm install stylus stylus-loader -g
2. 编译命令
# 单文件编译
stylus index.styl -o index.css
# 监听文件自动编译
stylus -w index.styl -o index.css
三、基础语法代码演示
3.1 变量与运算符
Stylus 无需分号、大括号、冒号,书写极简。
// 定义变量
primary-color = #2563eb
font-size-base = 14px
spacing = 8px
// 运算
box-padding = spacing * 2
border-radius = spacing / 2
.card
color primary-color
font-size font-size-base
padding box-padding
border-radius border-radius
编译后 CSS:
.card {
color: #2563eb;
font-size: 14px;
padding: 16px;
border-radius: 4px;
}
3.2 选择器嵌套 & 父级引用&
.nav
height 60px
background #fff
a
display inline-block
padding 0 12px
color #333
&:hover
color primary-color
&.dark
background #1a1a1a
a
color #fff
3.3 Mixin 混合宏(复用样式)
// 通用圆角阴影混合
card-shadow(radius = 6px)
border-radius radius
box-shadow 0 2px 12px rgba(0,0,0,0.08)
// 调用
.goods-card
card-shadow(10px)
padding 16px
3.4 函数与条件判断
// 颜色变暗函数
darken(color, num)
rgba(color, num)
// 条件判断
bg-type = dark
.box
if bg-type == dark
background #222
color #fff
else
background #f5f5f5
color #333
3.5 for 循环批量样式
// 循环生成间距类
for i in 1..6
.mt-{
i}
margin-top i * 4px
四、综合实战完整案例
index.styl
// 全局变量
theme-blue = #1677ff
text-gray = #666
base-space = 10px
// 混合
flex-center()
display flex
justify-content center
align-items center
// 页面容器
.page-wrap
width 1200px
margin 0 auto
padding base-space * 2
.title
font-size 20px
color theme-blue
margin-bottom base-space
.list-item
flex-center()
height 80px
border 1px solid #eee
margin-bottom base-space
.desc
color text-gray
margin-left base-space
编译输出核心CSS片段:
.page-wrap {
width: 1200px;
margin: 0 auto;
padding: 20px;
}
.page-wrap .title {
font-size: 20px;
color: #1677ff;
margin-bottom: 10px;
}
.page-wrap .list-item {
display: flex;
justify-content: center;
align-items: center;
height: 80px;
border: 1px solid #eee;
margin-bottom: 10px;
}
.page-wrap .list-item .desc {
color: #666;
margin-left: 10px;
}
五、项目使用注意事项
- 原生 CSS 兼容:如需保留分号、大括号,Stylus 完全兼容,两种写法可混用;
- 工程化适配:Vue/Webpack 项目安装 stylus-loader 后,直接在
<style lang="stylus">内编写; - 性能优化:大量循环代码建议编译时生成静态CSS,避免运行时计算;
- 变量作用域:块内变量仅当前选择器生效,全局变量统一写在文件顶部管理。
海量精选技术文档和实战案例持续更新,敬请关注【风骏时光少年】