5

I'm using scroll-margin-top on an anchor point to add space for my sticky header, but it is not supported in Safari.

These docs here - https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin point out this bug -

Scroll margin is not applied for scrolls to fragment target or scrollIntoView(), see bug 189265.

Aternate Name Uses the non-standard name: scroll-snap-margin

Is there any way around this bug?

jfc
  • 361
  • 3
  • 15
  • This sucks, it doesn't even work with extra markup where you add a class with position: absolute; top: -10rem; (which works in all other browsers) ... I haven't found a way around this other than just using padding above the scrolled element, which isn't a viable option. – anatolhiman Dec 31 '20 at 21:43
  • Scratch that, I re-tested my archaic-extra-markup-solution now in Safari 14.0.1 and it works. a inside or around my target element, with position: absolute and top: -100px does the trick. – anatolhiman Dec 31 '20 at 22:15

4 Answers4

2

This is the only solution I've found so far that works in both Safari and Firefox... Safari-specific selectors. It's not ideal, because using padding in the Safari element limits the styling you can use, but it beats everything I've tried otherwise.

.anchor { scroll-margin-top: 130px; }
.anchor::-webkit-full-page-media, .anchor:future, .anchor:root .safari_only { padding-top: 130px;}
1

I had the same problem with safari, here is my solution:

[id] {
    scroll-margin-top: 3ex;
    outline: 0 none;

    @media screen and (-webkit-min-device-pixel-ratio:0) {
        margin-top: -3ex;
        padding-top: 3ex;
    }
}
felipep
  • 2,442
  • 1
  • 28
  • 35
1

According to caniuse.com, scroll-margin-top is now supported in safari as well.

But I get a warning in VS Code from the webhint plugin to use scroll-snap-margin-top in order to support Safari 11+. There's also a related article & a stackoverflow question, which mentions the same thing.

You would have to use scroll-snap-margin-top instead of scroll-margin-top and this is because Safari has implemented it as part of the CSS scroll snap module, which means it is only to be used with scroll snap containers.

Gangula
  • 5,193
  • 4
  • 30
  • 59
0

scroll-margin-top indeed seems to work fine in Safari nowadays (tested on IOS). I landed on this topic as I had an issue with it in Safari but found that the references from Mozilla and "CanIuse" mentioned by others in this topic confirm that the later versions of Safari fully support scroll-margin-top.

In my case the issue in Safari was that I had set scroll-margin-top on an element which had "display: inline". Changing that to "display: inline-block" solved the issue. Strangely enough the issue didn't occur on desktop browsers, there it worked already with "display: inline", but for IOS (Safari and Chrome) it needed "display: inline-block". A very nasty issue to figure out, I hope this helps someone.

GoldyOnline
  • 519
  • 4
  • 4