Slow Learner's Quest

← Back to TIL 11 May 2025

Highlight Nav Link for Current Page in Astro

// in the JavaScpit part:
// the `pathname` is sth like - "/about"
const { pathname } = Astro.url;
// in the HTML part:
// such as the `slug` is "about"
<a class={pathname.slice(1) === slug ? 'active' : ''} href={`/${slug}`}>
  About
</a>

or

// in the HTML part:
<a
  aria-current={pathname.slice(1) === slug ? 'page' : 'false'}
  href={`/${slug}`}
>
  {name}
</a>

// in the CSS part:
a[aria-current="page"] {
  /* the styles for the active nav item */
}