以往,如要為清單中的每個同層元素套用不重複的樣式,必須使用複雜的 :nth-child 迴圈或 JavaScript 插入內嵌樣式。現代 CSS 提供 sibling-index() 和 sibling-count(),可直接在樣式表中執行這些計算,實現動態版面配置和色彩系統,並在新增或移除元素時自動調整。
動態色彩系統
你可以為每個子項計算專屬的色相或亮度值,在一組同層級元素中建立色譜。這樣一來,無論項目數量多寡,都能確保漸層效果一致。
.swatch {
/* Calculate hue by dividing the full 360deg circle by total siblings */
/* and multiplying by the current element's 1-based index */
background-color: hsl(
calc(360deg / sibling-count() * sibling-index()),
70%,
50%
);
}
對稱版面配置和扇形效果
如要建立對稱效果 (例如「扇形」或置中項目),請使用總數找出清單的中點。
.card {
/* Find the center index (e.g., 3 if there are 5 siblings) */
--center: calc((sibling-count() + 1) / 2);
/* Rotate items away from the center: negative for left, positive for right */
/* center element gets 0deg rotation */
transform: rotate(calc(10deg * (sibling-index() - var(--center))));
}
圓形和複雜定位
只要將這些函式與 CSS 三角函數 (sin()、cos()) 結合,就能將元素放在完美的圓形中,不需手動輸入座標。
.orb {
/* Calculate the angle for this item's position on a 360deg circle */
--angle: calc(360deg / sibling-count() * sibling-index());
--radius: 150px;
/* Set the pre-transformed position for all items to be centered */
position: absolute;
place-self: center;
/* Position each element around the parent center */
transform: translate(
calc(cos(var(--angle)) * var(--radius)),
calc(sin(var(--angle)) * var(--radius))
);
}
備用策略
如果系統不支援 sibling-index() 和 sibling-count(),請透過 JavaScript 插入 CSS 自訂屬性,提供備用方案。必要:搭配使用功能偵測和 CSS.supports(),確保指令碼只在必要時執行。
/* MANDATORY: Check for native support before applying fallback */
if (!CSS.supports('top: calc(sibling-index() * 1px)')) {
const items = document.querySelectorAll('.item');
items.forEach((item, index) => {
/* MANDATORY: Injected index must be 1-based to match native function */
item.style.setProperty('--sibling-index', index + 1);
item.style.setProperty('--sibling-count', items.length);
});
}
在 CSS 中,請以這些變數為基礎,並在 @supports 區塊中使用原生函式覆寫這些變數。必要:您必須將原生函式覆寫納入 @supports,確保變數在舊版瀏覽器中仍有效。
.item {
/* 1. Set base values using variables (from JS fallback) */
--index: var(--sibling-index);
--count: var(--sibling-count);
/* 2. Use the computed variables - replace this with your implementation-specific styles */
background-color: hsl(calc(360deg / var(--count) * var(--index)), 70%, 50%);
}
@supports (top: calc(sibling-index() * 1px)) {
.item {
/* 3. Override with native functions ONLY if supported */
--index: sibling-index();
--count: sibling-count();
}
}