在分頁選單中,您應向使用者提供視覺提示,讓他們知道自己位於哪個頁面。其中一個選項是在分頁下方加上底線。使用錨定定位,您可以在底線位置之間建立流暢的動畫。如果變更使用中分頁會載入新網頁,則不適用這項功能。
您也可以使用這個效果,在垂直分頁列中加入動畫圓點,表示目前使用的分頁。
在包含 <li> 元素的 <ul> 上,使用 ::before 虛擬元素建立底線。建議使用虛擬元素,因為這樣可以保持 DOM 乾淨,避免為了純裝飾效果而新增額外元素。
ul::before {
/* Use a pseudo-element on the container to represent the animated indicator */
content: '';
}
新增 anchor-name 屬性,並將值設為以 -- 開頭,讓有效的清單項目成為錨點。
li.active {
/* Make a unique anchor-name for the active element. */
anchor-name: --active;
}
使用與錨定標記上的 anchor-name 相符的 position-anchor,將底線繫結至有效項目錨定標記,並將其設為 position: absolute。
ul::before {
/* Tether the underline to the active element. */
position: absolute;
position-anchor: --active;
}
使用 inset 屬性和 anchor() 函式,根據錨點定位底線。
ul::before {
/* DO NOT use position-area, which can not be transitioned. */
/* Use calc() to offset the top slightly */
inset-block-start: calc(anchor(bottom) + .1lh);
inset-inline-start: anchor(left);
inset-inline-end: anchor(right);
}
新增高度和其他視覺樣式。
ul::before {
/* Apply your project's styles for the indicator */
block-size: .25lh;
background: red;
}
最後,在 inset 屬性上新增轉場效果。
ul::before {
@media (prefers-reduced-motion: no-preference) {
/* MANDATORY: The transition must be wrapped in a prefers-reduced-motion media query to respect user preferences. */
transition: inset .2s;
}
}
這只是視覺指標,不能取代適當的 aria-current="page" 或 aria-selected aria 值設定。
<!-- MANDATORY: Provide explicit assistive technology state alongside the visual tab underline -->
<nav aria-label="Primary">
<ul>
<li class="active">
<a href="/home" aria-current="page">Home</a>
</li>
<li>
<a href="/about">About</a>
</li>
</ul>
</nav>
備用策略
如果瀏覽器不支援錨點定位,請使用 border-bottom 新增底線。不會有動畫效果。
ul li.active {
@supports not (position-anchor: auto) {
/* Choose a color appropriate to the app theme. */
border-bottom: .25lh var(--primary) solid;
}
}