写过 CSS 的人都踩过这个坑——每次做交错动画都要手写 nth-child,今天两个 CSS 函数把这件事彻底原生化了

配列表动画的时候,你是不是也写过这种代码:给每个 nth-child(1)、nth-child(2)、nth-child(3)……手动设一个 –i 变量,然后用 calc(0.1s * var(–i)) 算延迟?列表短还好,七八个元素顶天了。一旦列表要动态增减,每次加一个 item 你都得回头改 CSS。

这个问题本质上不是 JavaScript 的问题——浏览器在渲染的时候本来就知道「这个元素在所有兄弟里排第几个、总共有多少个兄弟」,只是 CSS 一直没有提供接口让我们直接问它。

两个函数把这个信息直接暴露给了 CSS。

sibling-index():你在第几个

这个函数返回当前元素在所有兄弟节点中的位置,从 1 开始数。直接放在 calc() 里用就行:

li {
  transition-delay: calc(sibling-index() * 100ms);
}

第一个 li 延迟 100ms,第二个 200ms,第三个 300ms——不需要任何 nth-child,不需要任何 JavaScript 遍历,浏览器自己就算出来了。

sibling-count():你们一共几个

这个函数返回同级兄弟节点的总数,配合 sibling-index() 可以做比例计算:

li {
  width: calc(100% / sibling-count());
  background-color: hsl(
    calc(360deg / sibling-count() * sibling-index())
    70% 60%
  );
}

三个 item 平均分宽度、颜色均匀分布在色轮上;三十个 item 也一样,公式不变,浏览器按实际数量重新算一遍。

实战:交错入场动画

以前手写 nth-child 的完整写法大概是这样:

/* 旧方法:每个位置单独写 */
li:nth-child(1) { animation-delay: 0ms; }
li:nth-child(2) { animation-delay: 100ms; }
li:nth-child(3) { animation-delay: 200ms; }
li:nth-child(4) { animation-delay: 300ms; }
/* ……一直写到列表最大长度 */

现在两行搞定:

li {
  animation: fadeIn 0.4s ease both;
  animation-delay: calc(sibling-index() * 80ms);
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(12px); }
  to   { opacity: 1; transform: translateY(0); }
}

列表变成 5 个 item,动画自动变成 0/80/160/240/320ms;变成 10 个,延迟自动扩展到 720ms。CSS 自己跟着 DOM 走,不用改一行。

什么时候用它

sibling-index() 和 sibling-count() 最适合这几类场景:

  • 交错动画延迟( stagger )
  • 列表项编号( ::before { content: sibling-index() } )
  • 动态进度条( –progress: calc(sibling-index() / sibling-count()) )
  • 等宽网格布局( width: calc(100% / sibling-count()) )
  • 色轮分布(背景色按兄弟数量均分 hsl 色值)

兼容性和 fallback

这两个函数在 2026 年 8 月进入 Baseline,Chrome 138+、Firefox 154+、Safari 26.2+ 支持,全球约 70% 覆盖率。Firefox 是今年 8 月刚稳定发布的,所以在最近这个节点特别值得关注。

如果你的页面需要兼容旧版浏览器,用 @supports 做渐进增强:

/* 默认 fallback:手写 nth-child */
li:nth-child(1) { animation-delay: 0ms; }
li:nth-child(2) { animation-delay: 100ms; }
/* …… */

/* 支持的浏览器覆盖掉 */
@supports (animation-delay: calc(sibling-index() * 1ms)) {
  li { animation-delay: calc(sibling-index() * 100ms); }
}

一个容易踩的坑

sibling-index() 只数直接兄弟节点。如果你把每个 item 套了一层 wrapper,那 sibling-index() 会数 wrapper,而不是 item:

<!-- 每个 .item 套了 .wrapper 的情况 -->
<div class="wrapper"><div class="item"></div></div>
<div class="wrapper"><div class="item"></div></div>

这时候 sibling-index() 在 .item 上会全部返回 1(因为每个 item 都是自己 wrapper 的唯一子节点)。解决办法是把 sibling-index() 写到 wrapper 那一层,或者把 DOM 结构拍平。

下一步

打开浏览器的开发者工具,找一个你手头有列表组件的页面,把 nth-child 那些手写延迟删掉,换成 calc(sibling-index() * Nms)。感受一下「CSS 终于认识自己」的感觉。如果列表长度不确定或者会动态增减,这招特别管用。

评论区

0 条评论

登录后可评论。

小鹿·界面实验室 2567 阅读