DEV Community

Cover image for How can you create a Scroll To Top button with just HTML?.
Kavindu Santhusa
Kavindu Santhusa

Posted on

How can you create a Scroll To Top button with just HTML?.

Oh, today I'm going to introduce a silly trick. This is one of the first things I learned about HTML.

So without cheating😉, Here is the solution (as a tweet 🐦).

Please like and retweet if you love it.

This is a basic of HTML. Instead of fighting with JavaScript. We can use HTML to do it.

<a href="#">Scroll To Top</a>
Enter fullscreen mode Exit fullscreen mode

When you clicked this link the page jumps to the top immediately. So we can add smooth scrolling to page with one line of CSS.

:root { scroll-behavior: smooth; }
Enter fullscreen mode Exit fullscreen mode

This CSS line will enable smooth scroll for all the links in whole page. It's OK, because it's useful for most situations.

You can use CSS to create a floating scroll to top button.

.stt {
  position: fixed;
  right: 1rem;
  bottom: 1rem;
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  background: rgb(128, 128, 255) url("data:image/svg+xml;utf8,%3Csvg xmlns='' viewBox='0 0 384 512'%3E%3Cpath fill='currentColor' d='M352 352c-8.188 0-16.38-3.125-22.62-9.375L192 205.3l-137.4 137.4c-12.5 12.5-32.75 12.5-45.25 0s-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0l160 160c12.5 12.5 12.5 32.75 0 45.25C368.4 348.9 360.2 352 352 352z'%3E%3C/path%3E%3C/svg%3E") center no-repeat;
  box-shadow: 0 0.25rem 0.5rem 0 gray;
  opacity: 0.7;

.stt:hover {
  opacity: 0.8;

.stt:focus {
  opacity: 0.9;

.stt:active {
  opacity: 1;
Enter fullscreen mode Exit fullscreen mode

position makes it floating. right and bottom places it. border-radius makes it round. used a background color with up arrow head SVG as background image. opacity is used to show state. And it's useful because user can read the content behind the button.

Update your link

<a href='#' class="stt" title="scroll to top"></a>
Enter fullscreen mode Exit fullscreen mode

title is used to improve accessibility. And it shows a tooltip when hovered.

See the codepen.

Thanks for reading this article.
Follow me for more articles.

Discussion (0)