The CSS scroll-margin property

2023-12-18 #css

Last week I remembered the scroll-margin property existed.

I was adding anchors to the headings of a page so visitors can directly link to a section. However, when that link was visited, the heading was glued against the top of the viewport. I prefer some margin between the browser chrome and the text to let it breath.

There's a CSS property for that: scroll-margin. It does nothing in most cases, but when you visit a URL that points to an anchor on the page, it will offset the element from the viewport.

h2 {
scroll-margin-top: 1rem;
}

You can read all about scroll-margin in the MDN docs.