10

I have a problem with the css property scroll-margin-top (adds offset when scrolling to element on page). It's not working in all the cases, in particular, this case: when the elements with scroll-margin-top are inside a container with overflow: hidden.

What can be the reason? Is there a workaround?

skalta
  • 1,033
  • 1
  • 7
  • 18

1 Answers1

22

My problem was that the elements to which I had assigned the scroll-margin-top were sometimes in a container with overflow: hidden. As soon as the element is at the top and thus the scroll-margin protrudes from this container, the scroll-margin is also cut off by the overflow: hidden.

skalta
  • 1,033
  • 1
  • 7
  • 18
  • 3
    My god I spent a day debugging this same issue. Thanks for adding an answer here. And for the record, I think your question is clear or I wouldn't have found an answer! – jottin Jun 20 '22 at 17:04
  • Another reason why scroll-margin-top might not be working is if the element on which the scroll-margin-top is set has "display: inline". See: https://stackoverflow.com/a/73120680/15471585 – GoldyOnline Jul 26 '22 at 09:18
  • For me adding `tabindex="-1"` to the header solved the issue. – Anis Abboud Oct 31 '22 at 07:34
  • Does anyone have any suggestions for fixing this? (Thank you for spotting it, @skalta!) – Eliezer Berlin Feb 19 '23 at 14:24
  • @EliezerBerlin, perhaps you can look into using `overflow: clip` instead of `overflow: hidden` ? That might work for some situations, not entirely sure from the top of my head whether that also fixes the issue described here but it's worth a try? – GoldyOnline Feb 20 '23 at 18:59
  • I gave up and just `window.scroll() & -100px` instead of `element.scrollIntoView() & scroll-margin-top`. – Eliezer Berlin Feb 21 '23 at 11:18
  • For me, it didn't work because the element, to which it had to scroll, was shown by js and then scrolled into view immediately. Seems like chrome didn't have enough time to render the element and scrolled to its old place. Scrolling after 500ms timeout helped me. – Vincente Mar 29 '23 at 12:16