Sitemap

Say hello to CSS > sibling-index() & sibling-count()

4 min readJul 1, 2025
Press enter or click to view image in full size
Say hello to CSS > sibling-index() & sibling-count()

Introduction

Chrome VER.138 發表了一對我期待非常久的 CSS function — sibling-index() 以及 sibling-count()。簡單地說可以透過 sibling-* 來取得同層兄弟的總數以及本身於兄弟佇列中的序號,聽起來好似平淡無奇,但卻大大減少 web developers 長久以來的困擾。

Issue

比方說這個 msc-yoyo-menu,每個 element 會因為自身於兄弟佇列中的索引而有所變化,或是調整角度或是調整 animation delay,讓最終呈現得以完美呈現。

web component > msc-yoyo-menu

這類重複性質高的變化 web developer 可以搭配 calc() 來依照 element 於兄弟佇列索引參數來進行運算。

簡單導讀一下上面的 CSS:

  • LINE 11:設定 unit 總數。
  • LINE 14:設定初始角度。
  • LINE 17:透過 unit 總量去算出每個 unit 需要間隔的角度。
  • LINE 20:unit animation delay。
  • LINE 22:由於是要往上調整角度,所以設定角度乘數。
  • LINE 25 ~ 39:透過 has 去偵測且調整 count 的總量。
  • LINE 45 ~ 47:設定 unit 於兄弟佇列中的索引並利用該索引計算出 unit 需要旋轉的角度以及 animation delay 所需要的時間,讓它可以呈扇形依序展開。
  • LINE 51 ~ 65:由於每個 unit 於兄弟佇列的索引資訊沒有任何取得方式,所以只能窮舉依序設定 order 的值。

Web developers 最大痛點莫過於 LINE 25 ~ 39 以及 LINE 51 ~ 65 窮舉的部分,由於無法確切知曉 unit 總量以及 unit 自身的兄弟佇列索引,所以只能不斷地窮舉。不僅僅 code 不優雅亦可能產生不及或是太過的現象發生。

Solution

sibling-index() 以及 sibling-count() 支援以後,我們來看看上面的 code 可以怎樣改寫。

  • LINE 19 ~ 20:由於 sibling-count() 是根據設定的 element 進行運算,所以需要把原本的 count 搬到這裡面,連帶的 delta-deg 亦要在這裡進行設定。
  • LINE 22:原先 order 的設定可以直接從 sibling-index() 進行提取。

如此一來便完成了 refactor,再也不需要去窮舉進行 count & order 的複寫了。讓整段 code 簡約優雅許多。

How to detect browser support or not ?

可以透過 CSS at-supports 或是 Web API > CSS.supports 進行偵測:

Conclusion

以上便是筆者期待許久的 CSS function > sibling-index()、sibling-count()。等不及要將這份喜悅分享給大家,有機會的話不妨試試看吧!由於目前支援度不高,所以搭配 CSS supports 來進行 progressive enhancement 或許較為妥當~

Reference

--

--

Paul Li
Paul Li

Written by Paul Li

Paul is the lead programmer of the AMP project at Yahoo Taiwan and is always eager for modern web technologies. He is also focusing on UX for vivid user flow.

No responses yet