sibling-index()
sibling-index() CSS 函式返回一個整數,表示當前元素在 DOM 樹中相對於其所有同級元素的位置。返回的值是上下文子元素在其父元素中所有同級元素中的索引號,第一個子元素返回 1,最後一個子元素返回 Element.children 的 length。
注意:與 :nth-child() 偽類一樣,sibling-index() 從 1 開始,而不是 0。
試一試
--width: calc(sibling-index() * 30px);
--width: calc(sibling-index() * 20px);
--width: calc(sibling-index() * 10px);
--width: 100px;
<ul id="example-element">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
#example-element {
list-style-type: none;
padding: 0;
margin: 0 auto;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
#example-element > li {
text-align: center;
padding: 2px;
border-radius: 8px;
width: var(--width, calc(sibling-index() * 30px));
color: white;
background-color: hsl(
calc(360deg / sibling-count() * sibling-index()) 50% 50%
);
}
語法
css
sibling-index()
引數
sibling-index() 函式不接受引數。
返回值
一個整數;當前元素在 DOM 樹同級順序中的位置。
示例
動態列表寬度
此示例演示如何將 <ul> 中每個 <li> 項的寬度動態增加 50px。
HTML
html
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
CSS
css
li {
width: calc(sibling-index() * 50px);
background-color: #ffaaaa;
}
結果
順序動畫
將 sibling-index() 與 CSS 動畫結合開闢了新的可能性。在此示例中,透過根據元素在 DOM 中的順序設定 animation-delay,使元素的透明度按順序變化。
HTML
我們包含一個包含四個子元素的容器元素
html
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
CSS
我們將 fade-in 動畫應用於每個元素。我們使用 calc() 函式中的 sibling-index() 函式,根據源元素在源順序中的位置設定 animation-delay 的持續時間。animation-fill-mode 會在 animation-duration 到期之前應用動畫的 0% 關鍵幀。
css
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
li {
animation-name: fade-in;
animation-duration: 1s;
animation-iteration-count: 1;
animation-timing-function: linear;
animation-fill-mode: backwards;
animation-delay: calc(1s * sibling-index());
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
結果
規範
| 規範 |
|---|
| CSS 值和單位模組 Level 5 # funcdef-sibling-index |
瀏覽器相容性
載入中…