I'm trying to replace a JavaScript smooth scroll:
document.getElementById('my-element').scrollIntoView({ behavior: 'smooth' });
with a CSS one using scroll-behavior: smooth
However in my case, the "overflowing" element is the tag.
When I don't add
html {
scroll-behavior: smooth;
}
to my CSS, clicking on links to elements work fine in that the page actually scrolls to the element in question. But the scrolling is of course not "smooth".
However when I add the above CSS snippet and click on my <a href="#my-element" />
link. It does not scroll at ALL.
As soon as I remove the scroll-behavior: smooth
it starts working again...
Interestingly this seems to only be a problem in Chromium. Both Firefox and Safari scrolls smoothly when I add the scroll-behavior to the html tag. But it completely breaks the functionality of the link in Chrome.
I then tried adding a overflow-y: scroll; scroll-behavior: smooth;
and a set height to a container that surrounds the elements I want to scroll and that worked! Any scrolling using href inside that container became smooth ✅... This also confirms it is not a browser or OS setting I have that is disabling my smooth scrolling.
The feature does work for me! Just not when applied to the tag.
I don't want my container to be the one where the scrollbar is though.
How can I get scroll-behavior: smooth
to work on the level?
My html styles are pretty simple and I couldn't find anything that should interfere with scroll-behavior:
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
-webkit-text-size-adjust: 100%;
}
I did also try to move the scroll-behavior to the <body />
but that also didn't work.
I tried specifically giving my html tag an overflow-y: scroll
. But that made no difference.
and for sanity check, I also tried scroll-behavior: smooth !important;
but same thing.
Lastly I also tried adding:
* {
scroll-behavior: smooth;
}
as I've seen some comments mention this. But that does not work either.
I found the issue:
https://bugs.chromium.org/p/chromium/issues/detail?id=1299237&q=scrollIntoView&can=2
It is a Chrome bug where the JS function scrollIntoView({ behavior: smooth })
and scroll-behavior: smooth;
CSS property will be cancelled if there is another call or scroll action happening in an unrelated scrolling box.
In my case, I had a carousel that was using scrolling to animate the carousel items moving in a requestAnimationFrame
This bug was causing my smooth-scroll links to be cancelled on every tick due to the active scroll animation further down the page.
This bug has been open since Feb 19, 2022, still not fixed and haven't gotten any attention. So I will have to end up rewriting my carousel logic to use transform: translate
instead scrolling to resolve this issue for Chrome users.