Search code examples
cssscroll-margin-top

How does the CSS property "scroll-margin-top" and "scroll-padding-top" really work


At first, it looks simple, and at the end of scroll event, a margin (or padding) will be applied at the top.

This is useful when there is a sticky element at the top. Then when a link is clicked and scroll down to somewhere on the page, it's nice to have this element "skipped" by the scrolling.

This article explains it pretty well: https://css-tricks.com/fixed-headers-and-jump-links-the-solution-is-scroll-margin-top/

I could make it work on really simple examples, and that works. However, I am trying to make this work on a normal website, and I can't. I think there is something not clear for me (or in general?) about how it works.

Please have a look here: https://meowapps.com/media-cleaner/tutorial/#Media_Library_Scan

When a link is clicked on the right, it scrolls but the scroll-padding-top is completely ignored. I have tried many techniques, moving the CSS property in many different places in the code, but that doesn't do anything.

Do you see what's wrong? Ideally, it would be great to find real the cause and maybe have an explanation why it doesn't work in this case and describes what's that case actually is.


Solution

  • scroll-margin is not useful if scroll behavior is controlled by JS

    Looking at your page source, I found easy-table-of-contents WordPress plugin, which relies on smooth-scroll jQuery script. Also, I don't see scroll-behavior: smooth; in your body either (see this MDN page for reference).

    It looks to me that your anchor link is not controlled by CSS but by JavaScript. And, as you'd know, when something is controlled by JavaScript, any relevant style declaration via CSS might be ignored.

    What to do?

    I honestly don't know. Perhaps you could replace the table of contents plugin with something that gives you a finer control. Perhaps you could refactor the said plugin yourself. In any case, should you need to keep the jQuery dependence and a particular WP plugin, you might have a tough luck for this fix.