Fix drifting tab indicators by aligning them within the scrollable container's coordinate space.

Quick solution:

const left = tab.offsetLeft; animate(indicator, { left: `${left}px` }); 

Managing Coordinate Spaces

The primary cause of indicator drift is a mismatch between the measurement reference and the positioning context. The offsetLeft property returns the distance of the current element relative to its offsetParent. If your indicator is a child of the rail, offsetLeft provides the correct relative coordinate. If you use viewport-based measurements like getBoundingClientRect, you must manually subtract the container's scroll offset to maintain alignment. When building these components, developers often look for ways to simplify their architecture, such as Halving Codebase Duplication in Static Site Generators, to ensure interaction patterns remain maintainable as the project grows.

Handling Scroll and Motion

When a user selects a tab that is partially obscured, use scrollIntoView to bring the element into the visible area. However, be mindful of user preferences. Always wrap your animation logic in a check for the prefers-reduced-motion media query. If the user has requested reduced motion, disable the transition or set the indicator position instantly to avoid discomfort. You can use a library like Motion to handle these transitions efficiently.

Implementation Checklist

  • Verify that the indicator and the tabs share the same offsetParent to ensure offsetLeft returns consistent values.
  • Trigger a re-calculation of the indicator position on window resize events to account for layout shifts.
  • Ensure the rail container has position: relative so that absolute positioning of the indicator remains scoped to the rail.
  • Test keyboard navigation to ensure the indicator updates correctly when focus moves between tabs.
  • Confirm that the indicator remains clipped within the rail boundaries using overflow: hidden on the container.