Keeping Anchors Perfectly on :target

Mitchell Christ
Mitchell Christ
  • Web Dev
Table of Contents
  1. The basics
  2. When a Sticky Header Gets in the Way
  3. The fix
  4. 🎯 Closing thought
an olympic runner doing a long jump attempt over a "<a>" 3d text obstacle object at an olympic stadium, sports photography

Hyperlinks are a key feature of webpages. You can either jump to another webpage, or you can jump to a specific location on the same page.

The basics#

  1. Give the element you want to jump to an id attribute.
  2. Add an <a> tag with an href that matches that id.
  3. Use the CSS :target selector to style the element once it’s in view.

With this simple setup, clicking the "Skip to..." scrolls visitors right to your chosen section.

Pro tip: Add scroll-behavior: smooth; for a silky-smooth glide instead of a jarring jump.

When a Sticky Header Gets in the Way#

Let’s say you add a sticky header (and maybe a bit of Tailwind polish). Now when you click the jump link, the target element can hide under the header—oops.

That’s because the browser aligns the target to the very top of the viewport by default.

Pro tip: Animate your :target (e.g. fade out after a second or two) to give visitors a visual cue.

The fix#

Use the scroll-margin-* property to give the target element breathing room.
For example:

  • :target {
      scroll-margin-top: 56px; /* or calc(1lh + 1rem) */
    }

    A fixed value works, but what if your header height changes with viewport size? Set a dynamic CSS custom property instead.

    Pro tip: Add a small buffer if you’re picky about spacing:
  • :root {
      --header-height: 0px;
    }
    
    :target {
      scroll-margin-top: calc(var(--header-height) + 1rem);
    }

    Then update --header-height with a couple lines of JavaScript whenever the viewport resizes.

    🎯 Closing thought#

    Whether you’re styling a :target in CSS or aiming for the perfect bullseye in life, a little precision goes a long way. Stay on target, keep experimenting, and have fun breaking the (style) rules when it makes the hit even sweeter.

    a ship anchor falling onto the Target store

    Not sponsored. All trademarks belong to their owners—this bullseye is purely for laughs.

    Ship your next site faster—and type safer

    Built for developers who love clean structure and fast launches.