Skip to content

Instantly share code, notes, and snippets.

@devzom
Last active March 16, 2022 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devzom/1a7f7a84fc53221d8a1c501c6ecff10d to your computer and use it in GitHub Desktop.
Save devzom/1a7f7a84fc53221d8a1c501c6ecff10d to your computer and use it in GitHub Desktop.
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