0
(0)

Having a smooth scrolling to the top when the user clicked on a “scroll to top” button was usually done with a Javascript snippet that looked like this:

window.scrollTo({ top: 0, behavior: 'smooth' });

The golden rule is though that where you can use CSS instead of JS, there should CSS be used. So what do you need to make it work?

  • an anchor link
  • an element with an id attribute
  • a scroll-behavior: smoot CSS rule on html

On the beginning of our HTML, we add a <span> tag with the id=”top” and on the bottom of our document we create an anchor link that points toward our span with the id=”top”. Finally we add in the CSS the rule html { scroll-behavior: smooth }

HTML CODE:

<main>
        <span id="top" class="visually-hidden" aria-hidden="true"></span>
        <h1>Main title</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce fermentum accumsan nisi non euismod. Morbi in orci in tortor mattis tempor euismod eu odio. Vestibulum condimentum augue lectus, ac tincidunt sem congue vestibulum. Sed non vehicula magna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum aliquam laoreet elit quis faucibus. Nullam ultrices elit odio, et eleifend dolor fermentum a.</p>
       <a href="#top" class="jumpToTop"><span class="visually-hidden">Jump to top</span></a>
</main>

Notes: The <span> tag got a class visually-hidden, because we don’t need a visible element in our document for a “top anchor”, we just need it for functional purposes(to have a placeholder for our top position). We also need the aria-hidden=”true” attribute because we don’t want anything to be read out by the screenreader. You might ask, then why didn’t I use the display: none or the hidden attribute. The reason is, you can’t scroll towards a hidden element!

CSS CODE:

The most important part is adding scroll-behavior: smooth; on html tag. The rest of the CSS is only for design purposes.

Note: Instead of using an extra element for “marking up” the top position we could add an id on the body tag and it would still work:

But wait, there is a problem ! The id is added in the window location url. Now what?

Let’s use label-input pairs instead of anchor links:

Finally, no side-effects ! That’s it, enjoy the smoothness of the scroll from now on !

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in:

Tagged in:

, ,