Back to top button only with CSS. Smooth scroll only with CSS is possible?

Asked

Viewed 3,207 times

4

I know that here on the site there are numerous questions of Smooth Scroll and Button to "return to top" (back to top), but they all involve Javascript or jQuery, but this não is my goal.

I would like to do, or know, if today is possible smooth scrolling only with CSS. It is possible to make a smooth scroll only with CSS and use this method in a button of type Voltar para o Topo?

Just the button I send back to the top I got, now I’d like to put a smooth scrolling behavior from the page back to the top.

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
section {
    height: 300vh;
    background-image: linear-gradient(red, blue);
}
.btn {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 10px;
    right: 10px;
    width: 50px;
    height: 50px;
    background-color: #000;
    text-decoration: none;
}
.btn::after {
    content: "↑";
    font-size: 32px;
    font-weight: bold;
    color: aliceblue;
    transition: margin-top 250ms;
}
.btn:hover::after {
    margin-top:-8px;
}
<section></section>
<a href="#" class="btn"></a>

  • @Jopedroschmitz that he already has, you can run the code to see.

  • Thanks for the observation, I had tested but I guess I didn’t notice!

1 answer

8


Yeah, just stick it in, scroll-behavior: smooth;in html. https://www.w3schools.com/howto/howto_css_smooth_scroll.asp

If you don’t want to put in all the Scrolls on the page you can create a new css class and insert scroll-behavior: smooth; there and then assign that class to the ones you want.

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    scroll-behavior: smooth;
}
section {
    height: 300vh;
    background-image: linear-gradient(red, blue);
}
.btn {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 10px;
    right: 10px;
    width: 50px;
    height: 50px;
    background-color: #000;
    text-decoration: none;
}
.btn::after {
    content: "↑";
    font-size: 32px;
    font-weight: bold;
    color: aliceblue;
    transition: margin-top 250ms;
}
.btn:hover::after {
    margin-top:-8px;
}
<section></section>
<a href="#" class="btn"></a>

Remember that this method is not yet supported in most browsers, only more current versions of modern browsers are supporting, as can be seen on the website Can I Use.

  • great method, I think it would be valid to mention that the support in the browser is still quite scarce.

  • I hadn’t noticed that thanks :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.