Categories
CSS Design HTML Tips Web

Jump-to Links Done Right

A quick CSS tip to kick off the week: to stop jump-to links from touching the top of the page when clicked use the scroll-margin-top property. Using the CSS property will give your design a touch of breathing room.

h1[id]:focus
{
    scroll-margin-top: 1rem;
    outline: 0;
}

Now, you will not want the page scroll “snapping” scroll-margin-top creates to be always-on (you will only want it when a jump link is clicked). The key to targeting only jump-to links is to use tabindex="-1" and the :focus pseudo-class. These additions keep the scroll-margin property isolated to the jump-to link.

<body>
    <a href="#one">Jump to one</a>
    <h1 tabindex="-1" id="one">One</h1>
</body>

You can read more about scroll-margin-top in the MDN web docs.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.