Skip to content

Instantly share code, notes, and snippets.

@devzom
Last active Mar 16, 2022
Embed
What would you like to do?
CSS: Animated smooth anchor scroll with anchor margin
<!-- step 3 -->
<!-- It's important to add tabindex="-1" to all anchor tags -->
<section id="section1" tabindex="-1">Section 1</section>
/* step 1 */
html:focus-within {
/* smooth scroll on real scroll or anchor tag,
but not on search for word on webpage */
scroll-behavior: smooth;
}
/* respect user settings */
@media (prefers-reduced-motion) {
html:focus-within {
scroll-behavior: auto;
}
}
/* step 2 */
[id] {
/* add scroll-margin to all HTML tags with ID to top */
scroll-margin-top: 2rem;
}
/* look into step 3 in index.html */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment