Testing a "Back to top" pattern

A link directly after the main heading

You can test the "Back to top" link at the bottom of this page.

The basics

The accessible version of this pattern is simple. It just needs a fragment link, an id, and tabindex="-1" so the heading can receive focus.

<h1 id="top" tabindex="-1">Main heading</h1>
...
<p><a href="#top">Back to top</a></p>

The CSS provides a visible focus indicator when the heading receives focus:

h1[tabindex="-1"]:focus {
  outline: 3px solid red;
  outline-offset: 4px;
}

That is the basic pattern. It does not need JavaScript, and it keeps the viewport position, keyboard focus and the screen reader's reading position together. Keeping these aligned is an important part of making the pattern work well.

This test page adds smooth scrolling to that baseline, which is why it includes a small amount of JavaScript. The sections below look at the additional features and the trade-offs involved in each one.

Required

Good practice

These are not strict requirements, and they do not require JavaScript.

Highlight the destination

The focus ring shows where focus is. A brief flash can provide an additional cue that something has moved. Because Back to top can replace several screens of content at once, the destination may look quite different from what the user was just viewing.

A static focus ring can still take time to find, particularly for keyboard users and people using high zoom with only a small part of the page visible.

With an instant jump, focus and the visual change happen at the same time, so this cue only needs a few lines of CSS:

h1[tabindex="-1"]:focus {
  animation: flash 1s ease-out;
}

@keyframes flash {
  from { background-color: #ff0; }
  to   { background-color: transparent; }
}

The control itself

Optional: smooth scrolling

Smooth scrolling only needs a small amount of CSS and can help show how far the page has moved, rather than using an instant jump.

One thing to consider before adding it: smooth scrolling separates the moment focus moves from the moment the target comes into view. On its own, this is not necessarily a problem. However, if it is combined with the focus flash above, the flash may begin while the target is still off screen. The next section looks at how to coordinate the two.

Optional: coordinating the cue with smooth scrolling

The script on this page delays the yellow flash until the smooth scrolling has finished. If you are not combining the flash with smooth scrolling, you do not need this script.

Back to top