Back to Top
Scroll down the page and you’ll see the back to top pointer which, on this page, has it’s track element outlined.
To create this effect you need two elements: the link element and a track element in which the link floats.
The track is fixed to the page while the link tries to take a fixed position relative to the viewport but is constrained by the outer track.
Making the track
The track can be part of a conventional layout, like a grid or flexbox layout, or it could be set to position: absolute
. With this latter option you have to set the parent element to position: relative
, EVEN if it’s parent is the body element. (The position: absolute
is set relative to the viewport when the body has the default, position: static
, set. It needs to be relative to the whole page so it can extend right down to the bottom.)
Here is a basic layout.
<body>
<header id="top">Header stuff..</header>
<main>main content...</main>
<div class="to-top-track">
<a href="#top">top</a>
</div>
</body>
So first the CSS to create the track. The top: 110vh
value means it starts 10 viewport height units below the viewport. The bottom value means it is 5em’s above the bottom of the page.
body {
position: relative;
}
.to-top-track {
position: absolute;
top: 110vh;
bottom: 5em;
}
If the track was part of a grid or flexbox layout we might want to define the width but with position: absolute;
the width will be minimum anyway. The top: 110vh
means the track, and thus the link, is below the viewport when a page is loaded. As you scroll down the page the top of the track will come into the viewport allowing the link to become visible.
The bottom: 5em
sets how close the link can be to the bottom of the page. Here it set fairly high, which could be used to prevent the link from sinking in to the <footer>
for instance.
When setting up the track it can be helpful to make it visible by setting a background-color
, border
or outline
.
The CSS for the link can be as little as just two lines:
#top {
position: sticky;
top: 110vh;
}
The position: sticky
sticks the element to its nearest scrolling ancestor and containing block
Links
- Great in depth article on Modern CSS by Stephanie Eckles.