🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Components & Islands••By Komal Nakrani

Astro Scroll to Top: A Back-to-Top Button That Works

Add an Astro scroll to top button: a real #top link that works without JavaScript, shown after scrolling with IntersectionObserver, with reduced-motion support.

#Astro#Astro Scroll to Top#Components#Accessibility

The simplest Astro scroll to top button is a link to #top with html { scroll-behavior: smooth } in your CSS: it works without JavaScript and scrolls smoothly in every current browser. A few lines of script with IntersectionObserver then hide the button until the reader has scrolled down, and moving focus back to the top keeps keyboard users oriented.

Key Takeaways

  • Use a real link to an element with id="top", so the button works with JavaScript off.
  • Smooth scrolling belongs in CSS, wrapped in a prefers-reduced-motion check.
  • Show the button with an IntersectionObserver on a sentinel, not a scroll listener.
  • Move focus to the top target so the next Tab starts at the beginning of the page.

The component

---
// src/components/BackToTop.astro
---
<a href="#top" class="back-to-top" data-back-to-top aria-label="Back to top">
  <svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20">
    <path d="M10 15V5M5 10l5-5 5 5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
  </svg>
</a>

<script>
  const button = document.querySelector<HTMLAnchorElement>('[data-back-to-top]');
  const sentinel = document.getElementById('scroll-sentinel');

  if (button && sentinel) {
    new IntersectionObserver(([entry]) => {
      button.classList.toggle('is-visible', !entry.isIntersecting);
    }).observe(sentinel);

    button.addEventListener('click', () => {
      document.getElementById('top')?.focus({ preventScroll: true });
    });
  }
</script>

<style>
  .back-to-top {
    position: fixed;
    right: 1.25rem;
    bottom: 1.25rem;
    z-index: 30;
    display: grid;
    place-items: center;
    width: 2.75rem;
    height: 2.75rem;
    border-radius: 999px;
    background: var(--color-text, #111);
    color: var(--color-bg, #fff);
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.2s;
  }
  .back-to-top.is-visible,
  .back-to-top:focus-visible {
    opacity: 1;
    pointer-events: auto;
  }
</style>

Wire it into the layout

---
// src/layouts/BaseLayout.astro (excerpt)
import BackToTop from '../components/BackToTop.astro';
---
<body>
  <div id="top" tabindex="-1"></div>
  <Header />
  <main>
    <slot />
  </main>
  <div id="scroll-sentinel" aria-hidden="true" style="position:absolute; top:0; height:100vh; width:1px; pointer-events:none"></div>
  <BackToTop />
</body>
/* src/styles/global.css */
@media (prefers-reduced-motion: no-preference) {
  html { scroll-behavior: smooth; }
}

How it fits together:

  • #top with tabindex="-1" gives the link a target and lets the script move focus there. Without the focus move, a keyboard user who activates the button is scrolled up but their next Tab continues from the bottom of the page.
  • The sentinel covers the first screen. It’s absolutely positioned from the top of <body> and is one viewport tall, so it intersects until the reader has scrolled a full screen. Then !entry.isIntersecting turns true and the button appears. Change height to show it sooner or later, and keep the sentinel’s positioned parent as <body> (no position: relative wrapper), or the offset is measured from that wrapper.
  • :focus-visible shows the button even before it’s “visible”, so keyboard users who tab to it can see it.
  • Smooth scrolling is CSS, and only when the reader hasn’t asked for reduced motion.

With view transitions

With <ClientRouter />, put the setup inside document.addEventListener('astro:page-load', () => { ... }) so it runs after each navigation, since bundled scripts run once. Our view transitions guide explains the lifecycle, and the accessibility checklist covers focus and motion preferences in more depth. Pair it with a reading progress bar on long articles. Long-form blog themes are where a back-to-top button earns its place.

FAQ

How do I add a scroll to top button in Astro?

Add an element with id="top" at the start of <body> and a fixed-position link with href="#top". Enable smooth scrolling with scroll-behavior: smooth in CSS, and optionally show the link only after scrolling with an IntersectionObserver.

Do I need JavaScript for a back-to-top button?

No. A link to #top scrolls to the top in every browser, and CSS handles smooth scrolling. JavaScript only adds the show-after-scrolling behavior and moves keyboard focus to the top.

Why use IntersectionObserver instead of a scroll event?

A scroll handler runs many times per second while the reader scrolls. An observer fires only when the watched element enters or leaves the viewport, which is all a show-or-hide button needs.