Skip to content

Stylus CSS 预处理器详解 ​

一、Stylus 简介 ​

Stylus 是一个功能强大的 CSS 预处理器,由 TJ Holowaychuk 开发,采用 Node.js 编写。它提供了简洁灵活的语法,支持变量、混合宏、函数、嵌套规则等特性,能够大幅提升 CSS 的编写效率和可维护性。

Stylus 的特点 ​

特性说明
语法灵活支持省略大括号、分号、冒号等,可写 Python 风格的缩进语法
功能强大变量、混合宏、函数、条件语句、循环等编程特性
兼容性好输出标准 CSS,兼容所有浏览器
模块化支持文件导入,便于代码组织
内置函数丰富的内置函数库,处理颜色、数学运算等

二、安装与使用 ​

安装 ​

bash
# 全局安装
npm install -g stylus

# 项目本地安装
npm install stylus --save-dev

基本使用 ​

bash
# 编译单个文件
stylus input.styl -o output.css

# 监听文件变化自动编译
stylus -w input.styl -o output.css

# 压缩输出
stylus -c input.styl -o output.css

# 指定输出目录
stylus src/ -o dist/css/

在项目中配置 ​

javascript
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.styl$/,
        use: ['style-loader', 'css-loader', 'stylus-loader']
      }
    ]
  }
}

三、基本语法 ​

Stylus 的语法非常灵活,支持多种书写风格:

1. 标准CSS风格 ​

stylus
body {
  font-size: 14px;
  color: #333;
}

2. 省略大括号风格 ​

stylus
body
  font-size: 14px
  color: #333

3. 省略分号和冒号风格 ​

stylus
body
  font-size 14px
  color #333

4. 混合风格 ​

stylus
body {
  font-size: 14px
  color #333
}

四、变量 ​

1. 变量定义与使用 ​

stylus
// 定义变量
font-size = 14px
primary-color = #3498db
bg-color = #ecf0f1

// 使用变量
body
  font-size font-size
  color primary-color
  background-color bg-color

编译后:

css
body {
  font-size: 14px;
  color: #3498db;
  background-color: #ecf0f1;
}

2. 变量作用域 ​

stylus
global-color = #333

.container
  local-color = #666
  color local-color    // 使用局部变量

  .item
    color global-color // 使用全局变量

3. 属性查找 ​

stylus
#logo
  width: 100px
  height: width  // 引用同级的 width 值
  margin-left: @width / 2  // 使用 @ 访问父级属性

编译后:

css
#logo {
  width: 100px;
  height: 100px;
  margin-left: 50px;
}

五、选择器嵌套 ​

1. 基本嵌套 ​

stylus
.nav
  ul
    list-style: none
    margin: 0
    padding: 0

  li
    display: inline-block
    margin-right: 10px

  a
    text-decoration: none
    color: #333

    &:hover
      color: #007bff

编译后:

css
.nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
.nav li {
  display: inline-block;
  margin-right: 10px;
}
.nav a {
  text-decoration: none;
  color: #333;
}
.nav a:hover {
  color: #007bff;
}

2. 父选择器引用 (&) ​

stylus
.button
  background: #007bff
  color: white

  &:hover
    background: #0056b3

  &:active
    background: #004494

  &--primary
    background: #28a745

  &--danger
    background: #dc3545

  &.disabled
    opacity: 0.5
    cursor: not-allowed

编译后:

css
.button {
  background: #007bff;
  color: white;
}
.button:hover {
  background: #0056b3;
}
.button:active {
  background: #004494;
}
.button--primary {
  background: #28a745;
}
.button--danger {
  background: #dc3545;
}
.button.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

3. 部分选择器引用 ​

stylus
// 使用 ^[N] 引用父选择器的部分
.foo
  &__bar
    color: red

    ^[0]:hover &
      color: blue

编译后:

css
.foo__bar {
  color: red;
}
.foo:hover .foo__bar {
  color: blue;
}

六、混合宏 (Mixins) ​

混合宏是 Stylus 最强大的特性之一,允许定义可重用的样式块。

1. 基本混合宏 ​

stylus
// 定义混合宏
border-radius(n)
  -webkit-border-radius: n
  -moz-border-radius: n
  border-radius: n

// 使用混合宏
.button
  border-radius(5px)

编译后:

css
.button {
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

2. 带默认参数的混合宏 ​

stylus
// 定义带默认值的参数
box-shadow(x = 0, y = 0, blur = 5px, color = rgba(0, 0, 0, 0.3))
  -webkit-box-shadow: x y blur color
  -moz-box-shadow: x y blur color
  box-shadow: x y blur color

.card
  box-shadow()  // 使用默认值

.modal
  box-shadow(0, 10px, 20px, rgba(0, 0, 0, 0.5))  // 自定义值

3. 命名参数 ​

stylus
transition(property, duration = 0.3s, timing = ease)
  -webkit-transition: property duration timing
  -moz-transition: property duration timing
  transition: property duration timing

.element
  transition: (duration: 0.5s, property: all)

4. arguments 变量 ​

stylus
// arguments 包含所有传入的参数
box-shadow()
  -webkit-box-shadow: arguments
  -moz-box-shadow: arguments
  box-shadow: arguments

.card
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1)

5. 混合宏块 (@block) ​

stylus
// 使用 @block 接收样式块
media-query(condition)
  @media condition
    {block}

+media-query("(max-width: 768px)")
  .container
    width: 100%
    padding: 0 15px

编译后:

css
@media (max-width: 768px) {
  .container {
    width: 100%;
    padding: 0 15px;
  }
}

6. 常用混合宏示例 ​

stylus
// 清除浮动
clearfix()
  &::after
    content: ''
    display: table
    clear: both

// 文本截断
text-overflow()
  overflow: hidden
  text-overflow: ellipsis
  white-space: nowrap

// 多行文本截断
line-clamp(lines = 2)
  display: -webkit-box
  -webkit-line-clamp: lines
  -webkit-box-orient: vertical
  overflow: hidden

// Flex 居中
flex-center()
  display: flex
  justify-content: center
  align-items: center

// 绝对定位居中
absolute-center()
  position: absolute
  top: 50%
  left: 50%
  transform: translate(-50%, -50%)

// 使用示例
.container
  clearfix()

.title
  text-overflow()
  width: 200px

.description
  line-clamp(3)

.hero
  flex-center()
  height: 100vh

.modal
  absolute-center()

七、函数 ​

Stylus 支持自定义函数,可以返回值而不仅仅是样式。

1. 基本函数 ​

stylus
// 定义函数
add(a, b)
  a + b

// 使用函数
.container
  width: add(100px, 50px)  // 150px

2. 条件返回函数 ​

stylus
// 根据背景色返回合适的文字颜色
text-color(bg)
  if light(bg)
    return #333
  else
    return #fff

.button
  background: #333
  color: text-color(#333)  // 返回 #fff

.card
  background: #fff
  color: text-color(#fff)  // 返回 #333

3. 默认参数与多返回值 ​

stylus
// 默认参数
size(width, height = width)
  width: width
  height: height

// 多返回值
get-size()
  return 100px 200px

.element
  size: 50px      // width: 50px, height: 50px
  {get-size()}    // width: 100px, height: 200px

4. 递归函数 ​

stylus
// 计算 n 的阶乘
factorial(n)
  if n <= 1
    return 1
  else
    return n * factorial(n - 1)

.test
  z-index: factorial(5)  // 120

八、条件语句 ​

1. if/else if/else ​

stylus
theme = 'dark'

body
  if theme == 'dark'
    background: #1a1a1a
    color: #fff
  else if theme == 'light'
    background: #fff
    color: #333
  else
    background: #f5f5f5
    color: #666

2. 后置条件 ​

stylus
box-support = true

.box
  border: 1px solid #ccc if box-support
  padding: 10px unless box-support  // unless = if not

3. 三元运算符 ​

stylus
theme = 'dark'
bg-color = theme == 'dark' ? #1a1a1a : #fff

body
  background: bg-color

九、循环 ​

1. for 循环 ​

stylus
// 基本循环
for i in 1 2 3 4 5
  .col-{i}
    width: i * 20%

编译后:

css
.col-1 {
  width: 20%;
}
.col-2 {
  width: 40%;
}
.col-3 {
  width: 60%;
}
.col-4 {
  width: 80%;
}
.col-5 {
  width: 100%;
}

2. 范围循环 ​

stylus
// 1..5 包含 5,1...5 不包含 5
for i in 1..5
  .mt-{i}
    margin-top: i * 5px

3. 遍历列表 ​

stylus
colors = red green blue yellow

for color, i in colors
  .color-{i + 1}
    background: color

编译后:

css
.color-1 {
  background: #f00;
}
.color-2 {
  background: #008000;
}
.color-3 {
  background: #00f;
}
.color-4 {
  background: #ff0;
}

4. 遍历对象(哈希) ​

stylus
sizes = {
  small: 12px
  medium: 16px
  large: 20px
}

for name, size in sizes
  .text-{name}
    font-size: size

编译后:

css
.text-small {
  font-size: 12px;
}
.text-medium {
  font-size: 16px;
}
.text-large {
  font-size: 20px;
}

5. 实用循环示例 ​

stylus
// 生成栅格系统
columns = 12

.row
  clearfix()

  for i in 1..columns
    .col-{i}
      float: left
      width: (i / columns) * 100%

// 生成间距工具类
spacings = {
  '0': 0,
  '1': 0.25rem,
  '2': 0.5rem,
  '3': 1rem,
  '4': 1.5rem,
  '5': 3rem
}

for name, value in spacings
  .m-{name}
    margin: value
  .p-{name}
    padding: value
  .mt-{name}
    margin-top: value
  .mb-{name}
    margin-bottom: value

十、运算 ​

Stylus 支持丰富的运算操作。

1. 算术运算 ​

stylus
.container
  width: 100px + 50px    // 150px 加法
  height: 100px - 20px   // 80px 减法
  padding: 10px * 2      // 20px 乘法
  margin: 100px / 2      // 50px 除法

2. 单位转换 ​

stylus
body
  font-size: 16px
  line-height: 1.5em    // 自动转换为相对值
  width: 50% + 25%      // 75%

3. 颜色运算 ​

stylus
primary = #3498db

.button
  background: primary
  border-color: primary - 20%      // 变暗 20%

  &:hover
    background: primary + 20%      // 变亮 20%

  &:active
    background: primary - 10% * 2  // 变暗 20%

4. 比较运算 ​

stylus
a = 10
b = 20

if a < b
  .test
    color: red  // 会输出

5. 逻辑运算 ​

stylus
enabled = true
visible = true

if enabled and visible
  .element
    display: block

if enabled or visible
  .element
    opacity: 1

if not enabled
  .element
    display: none

十一、导入 (@import 与 @require) ​

1. @import ​

stylus
// 导入其他 Stylus 文件
@import 'variables'
@import 'mixins'
@import 'base'

// 导入 CSS 文件(会被原样输出)
@import 'normalize.css'

2. @require ​

stylus
// @require 只导入一次,避免重复
@require 'variables'
@require 'mixins'

3. 文件组织结构 ​

styles/
├── main.styl          # 主入口文件
├── variables.styl     # 变量定义
├── mixins.styl        # 混合宏
├── reset.styl         # 重置样式
├── base.styl          # 基础样式
├── layout.styl        # 布局样式
├── components/        # 组件样式
│   ├── buttons.styl
│   ├── forms.styl
│   └── cards.styl
└── utils.styl         # 工具类
stylus
// main.styl
@require 'variables'
@require 'mixins'
@require 'reset'
@require 'base'
@require 'layout'
@require 'components/*'
@require 'utils'

十二、内置函数 ​

Stylus 提供了丰富的内置函数。

1. 颜色函数 ​

stylus
color = #3498db

// RGB 操作
rgb(52, 152, 219)           // 创建颜色
rgba(52, 152, 219, 0.5)     // 带透明度
red(color)                  // 52 - 获取红色值
green(color)                // 152 - 获取绿色值
blue(color)                 // 219 - 获取蓝色值
alpha(color)                // 1 - 获取透明度

// HSL 操作
hue(color)                  // 色相
saturation(color)           // 饱和度
lightness(color)            // 亮度

// 颜色调整
lighten(color, 20%)         // 变亮 20%
darken(color, 20%)          // 变暗 20%
saturate(color, 20%)        // 增加饱和度
desaturate(color, 20%)      // 减少饱和度
fade-in(color, 0.5)         // 增加不透明度
fade-out(color, 0.5)        // 增加透明度
spin(color, 30)             // 旋转色相 30 度
mix(#f00, #00f)             // 混合两种颜色
tint(color, 50%)            // 与白色混合
shade(color, 50%)           // 与黑色混合

// 颜色判断
light(color)                // 是否为浅色
dark(color)                 // 是否为深色

2. 数学函数 ​

stylus
abs(-10px)          // 10px - 绝对值
ceil(5.3px)         // 6px - 向上取整
floor(5.7px)        // 5px - 向下取整
round(5.4px)        // 5px - 四舍五入
min(10px, 20px)     // 10px - 最小值
max(10px, 20px)     // 20px - 最大值
sum(1 2 3 4)        // 10 - 求和
avg(1 2 3 4)        // 2.5 - 平均值
sin(45deg)          // 正弦
cos(45deg)          // 余弦
tan(45deg)          // 正切
pow(2, 3)           // 8 - 幂运算
sqrt(16)            // 4 - 平方根

3. 字符串函数 ​

stylus
substr('hello', 0, 3)     // 'hel' - 截取子串
replace('hello', 'l', 'L') // 'heLLo' - 替换
split('a,b,c', ',')       // ('a' 'b' 'c') - 分割
join('-', 'a' 'b' 'c')    // 'a-b-c' - 连接

4. 列表函数 ​

stylus
list = 10px 20px 30px

push(list, 40px)          // 添加元素到末尾
pop(list)                 // 移除最后一个元素
shift(list)               // 移除第一个元素
unshift(list, 5px)        // 添加元素到开头
length(list)              // 3 - 列表长度
last(list)                // 30px - 最后一个元素

5. 类型判断函数 ​

stylus
is-string('hello')        // true
is-number(10px)           // true
is-color(#fff)            // true
is-list(1 2 3)            // true
is-ident('hello')         // true
type-of(10px)             // 'unit'
unit(10px)                // 'px'
unitless(10)              // true - 无单位

十三、@extend 继承 ​

1. 基本继承 ​

stylus
.message
  padding: 10px 15px
  border-radius: 4px
  font-size: 14px

.success
  @extend .message
  background: #d4edda
  color: #155724

.error
  @extend .message
  background: #f8d7da
  color: #721c24

编译后:

css
.message,
.success,
.error {
  padding: 10px 15px;
  border-radius: 4px;
  font-size: 14px;
}
.success {
  background: #d4edda;
  color: #155724;
}
.error {
  background: #f8d7da;
  color: #721c24;
}

2. 占位符选择器 ​

使用 $ 前缀定义占位符,不会输出到 CSS 中:

stylus
// 占位符选择器,不会输出到 CSS
$flex-center
  display: flex
  justify-content: center
  align-items: center

.hero
  @extend $flex-center
  height: 100vh

.modal
  @extend $flex-center
  position: fixed

编译后:

css
.hero,
.modal {
  display: flex;
  justify-content: center;
  align-items: center;
}
.hero {
  height: 100vh;
}
.modal {
  position: fixed;
}

十四、@keyframes 动画 ​

stylus
@keyframes fadeIn
  from
    opacity: 0
  to
    opacity: 1

@keyframes slideIn
  0%
    transform: translateX(-100%)
  50%
    transform: translateX(0)
  100%
    transform: translateX(100%)

.element
  animation: fadeIn 0.5s ease-in-out

十五、CSS 字面量 ​

当需要输出原生 CSS 或使用特殊语法时:

stylus
@css {
  .element {
    display: -webkit-flex;
    -webkit-flex: 1;
  }
}

十六、与 Flex 布局的对比 ​

Stylus 和 Flex 布局是两个不同层面的技术,下面从多个维度进行对比分析。

1. 概念对比 ​

对比项StylusFlex 布局
技术类型CSS 预处理器CSS 布局模式
作用层面开发工具/语法增强浏览器渲染/布局引擎
运行时机编译时(生成 CSS)运行时(浏览器渲染)
输出产物标准 CSS 文件视觉布局效果
核心目的提高 CSS 编写效率实现灵活的布局方案

2. 功能定位 ​

┌─────────────────────────────────────────────────────────┐
│                      前端开发技术栈                       │
├─────────────────────────────────────────────────────────┤
│                                                         │
│   Stylus (CSS 预处理器)                                 │
│   ├── 变量管理                                          │
│   ├── 混合宏复用                                        │
│   ├── 函数计算                                          │
│   ├── 嵌套语法                                          │
│   ├── 模块化导入                                        │
│   └── 编译优化                                          │
│                                                         │
│                    ↓ 编译生成 ↓                         │
│                                                         │
│   CSS (样式语言)                                        │
│   ├── 选择器                                            │
│   ├── 属性声明                                          │
│   └── 布局属性(包括 Flexbox)                          │
│                                                         │
│                    ↓ 浏览器解析 ↓                       │
│                                                         │
│   Flex 布局 (CSS 布局模式)                              │
│   ├── 容器属性:display, flex-direction, justify-content│
│   ├── 项目属性:flex-grow, flex-shrink, align-self      │
│   └── 布局效果:一维弹性布局                            │
│                                                         │
└─────────────────────────────────────────────────────────┘

3. 代码示例对比 ​

使用纯 CSS 编写 Flex 布局 ​

css
/* 纯 CSS 写法 */
.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.item {
  flex: 1 1 200px;
  order: 1;
  align-self: stretch;
}

.item:first-child {
  flex-grow: 2;
}

@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }

  .item {
    flex-basis: 100%;
  }
}

使用 Stylus 编写 Flex 布局 ​

stylus
// Stylus 写法 - 更简洁、可复用

// 定义 Flex 相关混合宏
flex-container(direction = row, justify = flex-start, align = stretch, wrap = nowrap)
  display: flex
  flex-direction: direction
  justify-content: justify
  align-items: align
  flex-wrap: wrap

flex-item(grow = 0, shrink = 1, basis = auto)
  flex: grow shrink basis

// 使用混合宏
.container
  flex-container(row, center, center, wrap)
  gap: 10px

.item
  flex-item(1, 1, 200px)
  order: 1
  align-self: stretch

  &:first-child
    flex-grow: 2

// 响应式处理
@media (max-width: 768px)
  .container
    flex-direction: column

  .item
    flex-basis: 100%

4. Stylus 增强 Flex 布局开发的方式 ​

(1) 封装 Flex 混合宏库 ​

stylus
// flex-helpers.styl - Flex 布局工具库

// Flex 容器
flex()
  display: flex

inline-flex()
  display: inline-flex

// 主轴方向
flex-row()
  flex-direction: row

flex-column()
  flex-direction: column

// 主轴对齐
justify-start()
  justify-content: flex-start

justify-center()
  justify-content: center

justify-end()
  justify-content: flex-end

justify-between()
  justify-content: space-between

justify-around()
  justify-content: space-around

// 交叉轴对齐
align-start()
  align-items: flex-start

align-center()
  align-items: center

align-end()
  align-items: flex-end

align-stretch()
  align-items: stretch

// 快捷居中
flex-center()
  display: flex
  justify-content: center
  align-items: center

// Flex 项目
flex-grow(n = 1)
  flex-grow: n

flex-shrink(n = 1)
  flex-shrink: n

flex-basis(width)
  flex-basis: width

flex-auto()
  flex: 1 1 auto

flex-none()
  flex: 0 0 auto

(2) 生成 Flex 工具类 ​

stylus
// 自动生成 Flex 工具类
flex-values = start, center, end, stretch, baseline, space-between, space-around

// justify-content 工具类
for value in flex-values
  .justify-{value}
    justify-content: unquote(replace('start', 'flex-start', replace('end', 'flex-end', '' + value)))

// align-items 工具类
for value in flex-values
  .align-{value}
    align-items: unquote(replace('start', 'flex-start', replace('end', 'flex-end', '' + value)))

// flex 值工具类
for i in 1..12
  .flex-{i}
    flex: i

编译后:

css
.justify-start {
  justify-content: flex-start;
}
.justify-center {
  justify-content: center;
}
.justify-end {
  justify-content: flex-end;
}
/* ... */

.align-start {
  align-items: flex-start;
}
.align-center {
  align-items: center;
}
.align-end {
  align-items: flex-end;
}
/* ... */

.flex-1 {
  flex: 1;
}
.flex-2 {
  flex: 2;
}
/* ... */
.flex-12 {
  flex: 12;
}

(3) 响应式 Flex 布局 ​

stylus
// 断点定义
breakpoints = {
  sm: 576px,
  md: 768px,
  lg: 992px,
  xl: 1200px
}

// 响应式 Flex 容器
responsive-flex()
  display: flex
  flex-wrap: wrap

  for name, width in breakpoints
    @media (min-width: width)
      flex-direction: row

// 使用
.grid
  responsive-flex()
  gap: 20px

5. 对比总结表 ​

维度StylusFlex 布局
本质CSS 预处理工具CSS 布局方案
解决的问题CSS 语法缺陷、代码复用、维护性元素排列、对齐、分布问题
学习曲线需要学习新语法和特性需要理解布局概念和属性
浏览器兼容编译后兼容所有浏览器现代浏览器支持良好
开发效率通过变量、混合宏提高效率通过声明式属性快速布局
代码组织支持模块化、嵌套、继承标准 CSS 选择器结构
可维护性高(变量统一管理、混合宏复用)中等(依赖命名规范)
调试方式需要查看编译后的 CSS浏览器开发者工具直接调试

6. 实际开发中的关系 ​

实际开发流程:

┌──────────────┐    ┌──────────────┐    ┌──────────────┐
│   Stylus     │    │    CSS       │    │   Flexbox    │
│   源代码     │ -> │   编译产物   │ -> │   布局效果   │
└──────────────┘    └──────────────┘    └──────────────┘
      │                    │                   │
      ▼                    ▼                   ▼
  使用变量、          标准 CSS          浏览器渲染
  混合宏、           样式文件          弹性布局
  嵌套语法

关键理解:

  1. Stylus 是工具,Flex 是技术:Stylus 帮助更高效地编写 CSS(包括 Flex 属性),而 Flex 是 CSS 的一种布局模式。

  2. 可以协同使用:在实际项目中,Stylus 可以封装 Flex 相关的混合宏,让 Flex 布局的编写更加便捷和可维护。

  3. 不同层面:

    • Stylus 解决的是 开发体验 问题
    • Flex 解决的是 布局实现 问题
  4. 最佳实践:使用 Stylus 封装 Flex 布局的常用模式,创建可复用的布局组件库。


十七、最佳实践 ​

1. 项目结构组织 ​

project/
├── src/
│   └── styles/
│       ├── index.styl          # 入口文件
│       ├── settings/
│       │   ├── variables.styl  # 变量定义
│       │   └── colors.styl     # 颜色配置
│       ├── tools/
│       │   ├── mixins.styl     # 混合宏
│       │   └── functions.styl  # 函数
│       ├── generic/
│       │   ├── reset.styl      # 重置样式
│       │   └── base.styl       # 基础样式
│       ├── elements/
│       │   ├── buttons.styl    # 按钮样式
│       │   ├── forms.styl      # 表单样式
│       │   └── typography.styl # 排版样式
│       ├── components/
│       │   ├── card.styl
│       │   ├── modal.styl
│       │   └── navbar.styl
│       └── utilities/
│           ├── flex.styl       # Flex 工具类
│           └── spacing.styl    # 间距工具类
└── dist/
    └── css/
        └── main.css            # 编译输出

2. 变量命名规范 ​

stylus
// 颜色变量 - 使用语义化命名
color-primary = #007bff
color-secondary = #6c757d
color-success = #28a745
color-danger = #dc3545
color-warning = #ffc107
color-info = #17a2b8

// 文本颜色
color-text-primary = #212529
color-text-secondary = #6c757d
color-text-muted = #adb5bd

// 间距变量 - 使用层级命名
spacing-xs = 0.25rem
spacing-sm = 0.5rem
spacing-md = 1rem
spacing-lg = 1.5rem
spacing-xl = 3rem

// 断点变量
breakpoint-sm = 576px
breakpoint-md = 768px
breakpoint-lg = 992px
breakpoint-xl = 1200px

// 字体变量
font-family-base = -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto
font-size-base = 1rem
font-size-sm = 0.875rem
font-size-lg = 1.25rem
line-height-base = 1.5

3. 混合宏最佳实践 ​

stylus
// 命名清晰,参数有默认值
transition(property = all, duration = 0.3s, timing = ease, delay = 0s)
  transition: property duration timing delay

// 支持多值
box-shadow(shadows...)
  -webkit-box-shadow: shadows
  box-shadow: shadows

// 文档注释
/*
 * 创建响应式容器
 * @param {String} max-width - 最大宽度
 * @param {String} padding - 内边距
 */
container(max-width = 1200px, padding = 15px)
  max-width: max-width
  margin-left: auto
  margin-right: auto
  padding-left: padding
  padding-right: padding

十八、常见问题与解决方案 ​

1. 编译错误排查 ​

stylus
// 问题:变量未定义
// 解决:确保变量在使用前定义,或使用默认值
color = color || #333

// 问题:混合宏参数类型错误
// 解决:添加类型检查
border-radius(radius)
  if typeof(radius) == 'unit'
    border-radius: radius
  else
    error('border-radius expects a unit value')

2. 性能优化 ​

stylus
// 避免过度嵌套(最多 3-4 层)
// 不推荐
.container
  .wrapper
    .content
      .item
        .link
          color: red

// 推荐
.container .item .link
  color: red

// 使用 @extend 减少重复代码
// 但注意不要过度使用,可能导致 CSS 膨胀

3. 调试技巧 ​

stylus
// 使用 p() 函数输出调试信息
p('变量值:', color-primary)
p('列表长度:', length(colors))

// 使用 @warn 输出警告
if not color
  @warn 'color 变量未定义'

总结 ​

Stylus 作为一款功能强大的 CSS 预处理器,通过变量、混合宏、函数、嵌套等特性,极大地提升了 CSS 的编写效率和可维护性。与 Flex 布局相比,两者处于不同的技术层面:Stylus 是开发工具层面的语法增强,而 Flex 是运行时层面的布局方案。在实际项目中,两者相辅相成,可以使用 Stylus 封装 Flex 布局的常用模式,实现更高效、更可维护的前端开发。

基于 VitePress 的本地知识库