Last active
March 16, 2022 13:55
-
-
Save devzom/1a7f7a84fc53221d8a1c501c6ecff10d to your computer and use it in GitHub Desktop.
CSS: Animated smooth anchor scroll with anchor margin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- step 3 --> | |
<!-- It's important to add tabindex="-1" to all anchor tags --> | |
<section id="section1" tabindex="-1">Section 1</section> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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