Secluded.Site

Adding A (Better) Scroll To Top Button Without JavaScript

Reading Time: 2 minutes | Published: 2020-05-11 | Last Edited: 2024-10-18

100 Days to Offload HTML CSS Websites

I’m a fan of using as little JavaScript as feasible on a website and implementing a scroll-to-top button in JS is just ridiculous. Nevertheless, there seems to be a plethora of copypasta for it so I thought I would write about implementing one in pure HTML and CSS. The title is just a playful poke at Kev Quirk who recently posted about exactly the same thing but with different styling 😉

HTML

There’s only one attribute to add to an existing HTML tag near the top of your page and a single line for the button itself.

For the attribute, you’ll need to use an ID. When the button is clicked, the user will be taken to whatever element has this attribute. For my site, I simply added it to the header at the very top.

<header class="header" id="top">

All that’s required for the button is:

<a href="#top"><button class="top">Top</button></a>

CSS

The basic HTML above is exactly the same as what Kev’s article has. The CSS is where ours will diverge. Having a button at the very bottom of the page is perfectly fine but I use my site as more than a blog; it’s reasonable to expect visitors to simply search for a link or whatever else and move on. Having a floating button that stays in the same place as the user scrolls is a good way to facilitate this.

.top {
  position: fixed;
  bottom: 10px;
  right: 10px;
  max-width: 50px;
  max-height: 50px;
  width: 100%;
  height: 100%;
  padding: .5px;
  border-radius: 8px;
  justify-content: center;
  background: #3b3d42;
  font-size: 1rem;
  font-weight: 800;
  text-decoration: none;
  cursor: pointer;
}

The position, bottom, and right lines are what tell your browser to render the item in the bottom right. The position is fixed so that means we can put it wherever on the page we want and it will stay there as the user scrolls. right and bottom say that the element is to be positioned 10 pixels above the bottom of the page and 10 pixels from the right. It’s rather hidden on desktop but I’m not expecting desktop users to click it very often; that’s what the Home key is for, after all, and it works across every website. I’m expecting mobile users to make use of it the most.


This was posted as part of #100DaysToOffload, an awesome idea (dead link to fedi post) from Kev Quirk. If you want to participate, just write something every day for 100 days and post a link on social media with the hashtag!


This is a self-hosted Commento server that integrates with Akismet for spam filtration. Comments that make it through are still subject to moderator (me) approval before they're displayed publicly.