Back to top
A back-to-top link takes the reader from far down a long page straight back to the start.
It links to #top, which needs no id: it always means the top of the document.
Scroll down this page and a button appears in the bottom corner.
In the corner
Put the link straight in the body, after main. No class is
needed: a link to #top in that place becomes a round button that rides
along the bottom corner of the screen as the page scrolls. At the end of the page it
comes to rest above the footer, so it never covers the footer's own links.
It is the button at the bottom right of this page. Because it rides on the page itself, it cannot sit in a box, so the box beside the code is a stand-in: a small scrolling area with a round link that stays in its bottom corner. Its link goes to the top of this page.
The start of a long page.
The reader scrolls down.
And further down.
And further still.
Far from the top now.
The end of the page.
↑<main>…</main>
<a href="#top" aria-label="Back to top">↑</a>
<footer>…</footer>
Fading in
At the top of the page there is nothing to go back to, so the button starts hidden and fades in over the first few hundred pixels of scrolling. This uses a scroll-driven animation, which needs no script. In a browser without scroll-driven animations the button simply shows all the time.
body > a[href$="#top"] {
animation: top-in linear both;
animation-timeline: scroll(root);
animation-range: 0 320px;
}
@keyframes top-in { from { opacity: 0; visibility: hidden; } }
An ordinary link
Anywhere else, a link to #top is a plain link, for the end of a long
article or the foot of each section in a reference page.
<p><a href="#top">Back to top</a></p>
Accessibility
- A name
- The button shows only an arrow, so
aria-label="Back to top"gives it a name a screen reader can read. A text link needs no label. - Focus
- Following the link moves the keyboard's starting point to the top as well, so the next Tab goes to the first link on the page.
- Size
- The button is 44 pixels across, big enough to hit with a finger.
- Motion
- The page glides back to the top, unless the reader has asked their system for reduced motion, in which case it jumps.