ในเมนูแท็บ คุณควรให้คำแนะนำแบบภาพแก่ผู้ใช้เกี่ยวกับหน้าเว็บที่กำลังดูอยู่ วิธีหนึ่งคือการขีดเส้นใต้แท็บ การจัดตำแหน่ง Anchor ช่วยให้คุณสร้างภาพเคลื่อนไหวที่ราบรื่นระหว่างตำแหน่งของเส้นใต้ได้ วิธีนี้จะใช้ไม่ได้เมื่อการเปลี่ยนแท็บที่ใช้งานอยู่โหลดหน้าเว็บใหม่
นอกจากนี้ คุณยังใช้เอฟเฟกต์นี้เพื่อเพิ่มจุดเคลื่อนไหวเพื่อระบุแท็บที่ใช้งานอยู่ในแถบแท็บแนวตั้งได้ด้วย
สร้างขีดเส้นใต้โดยใช้องค์ประกอบจำลอง ::before ใน <ul> ที่มีองค์ประกอบ <li> การใช้องค์ประกอบจำลองเป็นแนวทางที่แนะนำเนื่องจากจะช่วยให้ DOM สะอาดและหลีกเลี่ยงการเพิ่มองค์ประกอบเพิ่มเติมสำหรับเอฟเฟกต์ตกแต่งเท่านั้น
ul::before {
/* Use a pseudo-element on the container to represent the animated indicator */
content: '';
}
ทำให้รายการที่ใช้งานอยู่เป็น Anchor โดยเพิ่มพร็อพเพอร์ตี้ anchor-name ซึ่งมีค่าที่ขึ้นต้นด้วย --
li.active {
/* Make a unique anchor-name for the active element. */
anchor-name: --active;
}
เชื่อมโยงเส้นใต้กับ Anchor ของรายการที่ใช้งานอยู่ด้วย position-anchor ที่ตรงกับ anchor-name ใน Anchor และทำให้เป็น position: absolute
ul::before {
/* Tether the underline to the active element. */
position: absolute;
position-anchor: --active;
}
จัดตำแหน่งขีดเส้นใต้ให้สัมพันธ์กับ Anchor โดยใช้พร็อพเพอร์ตี้ 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 aria-current="page" หรือ aria-selected ที่เหมาะสม
<!-- 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>
กลยุทธ์สำรอง
หากเบราว์เซอร์ไม่รองรับการจัดตำแหน่ง Anchor ให้ใช้ border-bottom เพื่อเพิ่มขีดเส้นใต้ โดยจะไม่มีภาพเคลื่อนไหว
ul li.active {
@supports not (position-anchor: auto) {
/* Choose a color appropriate to the app theme. */
border-bottom: .25lh var(--primary) solid;
}
}