Home > Mobile >  smooth scroll transition upon click using CSS only (no JavaScript allowed)
smooth scroll transition upon click using CSS only (no JavaScript allowed)

Time:04-18

I'm trying to make a smooth scroll upon click the button (up) as in the gif: https://elzero.org/wp-content/uploads/2021/04/scroll-to-top-pure-css.gif

the thing is, I'm not allowed to use JavaScript for that, so only HTML and CSS and I don't seem to be able to find a relevant pseudo-class for that. Can any one please help? here is my HTML:

<a href="#one">Up</a>
<p id="one">One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>

And here's the CSS:

p {
    margin-bottom: 600px;
}

a {
    text-decoration: none;
    background-color: red;
    color: white;
    padding: 5px;
    position: fixed;
    bottom: 40px;
    right: 40px;
    transition: 1s all linear;
    -webkit-transition: 1s all linear;
    -moz-transition: 1s all linear;
    -ms-transition: 1s all linear;
    -o-transition: 1s all linear;
}

CodePudding user response:

You can use scroll-behavior: smooth;

html {
  scroll-behavior: smooth;
}
p {
    margin-bottom: 600px;
}

a {
    text-decoration: none;
    background-color: red;
    color: white;
    padding: 5px;
    position: fixed;
    bottom: 40px;
    right: 40px;
    transition: 1s all linear;
    -webkit-transition: 1s all linear;
    -moz-transition: 1s all linear;
    -ms-transition: 1s all linear;
    -o-transition: 1s all linear;
}
<a href="#one">Up</a>
<p id="one">One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>

  • Related