Advertisement

CSS Anchor Positioning Navigation Effect

| by Vladimir | 2 min read | code by Kevin Powell
A11y Ready Advanced

Tech & Dependencies

HTML CSS

Features

  • Zero JavaScript
  • CSS Anchor Positioning
  • Spring Animations
  • Glassmorphism

Browser Support

Chrome 125+ Edge 125+

Core

This CSS Anchor Positioning Navigation Effect is a masterclass in modern web standards, achieving a complex “sliding highlight” interaction entirely without JavaScript. By leveraging the new Anchor Positioning API alongside the :has() selector, the component allows a single background element to tether itself to whichever menu item is currently hovered, creating a premium, app-like feel with minimal code overhead.

Core Technique (The “How”)

The functionality relies on the browser’s ability to identify a specific element as an “anchor” and then position another element relative to its boundaries.

1. Dynamic Anchor Assignment

The magic starts with the anchor-name property. Instead of hardcoding an anchor to a single element, we apply it dynamically. When any link (a) is hovered, it is assigned the name --test. Simultaneously, we use the :has() selector on the parent ul to provide a fallback anchor when no items are hovered, ensuring the indicator returns to a neutral state.

/* Assign anchor to the hovered link */
a:hover {
  anchor-name: --test;
}

/* Fallback anchor when nothing is hovered */
ul:has(:not(:hover)) {
  anchor-name: --test;
}

2. Tethering the Indicator

The nav::before and nav::after pseudo-elements act as the visual highlight. They use position-anchor: --test to acknowledge the current anchor. By using the anchor() function in the positioning properties (top, left, etc.), these pseudo-elements automatically stretch and move to match the coordinates of the hovered link.

nav::after {
  position: absolute;
  position-anchor: --test;
  
  /* Match the link's edges */
  top: anchor(top);
  left: anchor(left);
  right: anchor(right);
  bottom: anchor(bottom);
}

3. Advanced Easing with linear()

To make the movement feel organic, the snippet utilizes the new linear() easing function. This allows for a multi-point easing curve that simulates a spring-loaded bounce. Unlike standard ease-in-out, this curve provides physical momentum, making the highlight feel tactile as it “snaps” between navigation items.

Browser Support

This component represents the absolute bleeding edge of CSS. In unsupported browsers, the navigation remains perfectly functional and accessible as a standard list of links, while users on modern Chromium browsers enjoy a high-performance, script-free animation experience.

Advertisement