Better Smooth Scroll With CSS

Better Smooth Scroll With CSS

ยท

2 min read

Hello beautiful peeps ! Lately, I have been seeing a lot of devs posting about how smooth scroll effect can be achieved with just 1 line of CSS.

html {
 scroll-behavior: smooth;
}

That's awesome, isn't it ? But this causes an accessibility and functionality issue.

It breaks Chrome's in-site search functionality and can cause issues for people with vestibular disorders.

To fix these issues use the code below -

@media(prefers-reduced-motion: no-preference) {

  html {
    animation: smoothScrollOne 1s;
  }

  html:focus-within {
    animation-name: smoothScrollTwo;
    scroll-behavior: smooth;
  }

  @keyframes smoothScrollOne {
     from,
     to {
       scroll-behavior: smooth;
     }
  }

  @keyframes smoothScrollTwo {
     from,
     to {
       scroll-behavior: smooth;
     }
  }
}

Credits to the solution presented in these articles -

Fixing Smooth Scrolling & Page Search

Fixing Smooth Scrolling with Find-on-Page

Happy Coding ๐Ÿš€