FSCSS 循环:@arr、%n()、rpt() 和 inline()

FSCSS 循环把数组展开成属性、选择器或值片段。它们既能在编译期(CLI)运行,也能在浏览器运行时运行,浏览器最终看到的始终是纯 CSS。

一、环境准备

浏览器里直接引入运行时:

<script src="https://cdn.jsdelivr.net/npm/fscss@1.2.5/runtime.min.js" async></script>

或者走编译路线:npm install -g fscss@1.2.5 → fscss in.fscss out.css。

二、经验法则

  • 数组采用从 1 开始的索引。
  • [] 表示遍历;[n] 是固定索引。
  • 索引列表:count(@arr.name!.length) 或 count(n, 1)。
  • 在很多循环驱动的规则之前放一条 empty{ /* preserve */ },这样中间的标记就不会被当成选择器。
  • %n → 属性 · rpt + @arr[] → 选择器 · inline("@arr[] { }") → 值内部的片段。

三、属性循环 —— %n()

把同一个值赋给多个属性:

@arr sizing[width, height, max-width, max-height]
$sizing: @arr.sizing!;

.box {
  bg: red;
  %4($sizing.list[: 200px;])
}

→ width / height / max-width / max-height: 200px.
经典写法:%2(width, height[: 100px;])。另有 1.2.5 简写写法。

四、自动索引 —— :nth-child

@arr delays[0.1s, 0.3s, 0.5s, 0.7s]
@arr colors[#ef4444, #f59e0b, #10b981, #3b82f6]
@arr indexes[count(@arr.colors!.length, 1)]

empty{ /* preserve */ }

.loading-dot:nth-child(@arr.indexes[]) {
  $index: @arr.indexes[];
  animation: bounce 1.5s infinite @arr.delays[$index!];
  background: @arr.colors[$index!];
}

每个索引对应一条规则——错开的延迟和颜色,不用复制粘贴。

五、嵌套选择器 —— rpt()

@arr colors[orange, purple, indigo, blue]
@arr levels[count(@arr.colors!.length)]

empty{ /* preserve */ }

rpt(@arr.levels[], "div ") {
  background: @arr.colors[@arr.levels[]];
  padding: 10px;
  border-radius: 10px;
  color: #fff;
}

→ div、div div、div div div、…… 官方另有嵌套循环指南。

六、值片段 —— inline()

在一条声明内部使用循环(自定义属性、clip-path、图表多边形):

@arr values[10, 20, 30, 40]
@arr idx[count(@arr.values!.length, 1)]

inline("empty{}
@arr.idx[] {
  $i: @arr.idx[];
  --val-@arr.idx[]: @arr.values[$i!]px;
}")

配合 num() 做间距运算。

七、empty{ /* preserve */ } 的作用

循环的内部结构可能看起来像选择器。在前面放一条:

empty{ /* preserve */ }

就能让 rpt / 自动索引 / inline 这些块不去吞掉周围的结构(1.2.1+)。

八、安装

npm install fscss

如果这篇帮你少踩了坑,点个赞、收藏一下,下次要用时好翻。关注「山岚的运维笔记」,继续看更多前端实战。