锚点定位标签页下划线

在标签页菜单中,您应向用户提供视觉提示,让他们知道自己位于哪个页面。一种方法是为标签页添加下划线。借助锚点定位,您可以在下划线的位置之间创建流畅的动画。如果更改活动标签页会加载新网页,则此操作无效。

您还可以使用此效果添加动画圆点,以指示垂直标签页栏中的活动标签页。

在包含 <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;
}

使用边衬区属性和 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;
  }
}