Use CSS Scroll Behavior for Animated Anchor Scrolls

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

In this lesson, we take a look at how to implement animated anchor scrolling using CSS scroll-behavior. We can do this whilst respecting our users' preference for motion and in a way that shouldn't annoy them when searching the page.

Jhey Tompkins: [0:00] Here we have a page with some anchor tags that are pointing at headings on our page, which relate to these sections. By clicking an anchor tag, the browser will take us to that section. If we want to apply a transition to that navigation, we can use html { scroll-behavior: smooth; }. Now, when we click one of our anchor tags, the browser will transition that navigation.

[0:20] That's great, but what if you wanted to navigate through some inline search results? You'll get the transition each time, and that could get annoying for your users. To combat this, we can use the pseudo selector focus-within, and now the browser won't transition between our search results. However, now we've lost the transition when using the anchor text too.

[0:40] To fix that, we can use tabindex="-1" on each of our headings. Now, we have the navigation transitions back for our anchor tags. It's down to how you want to style the outlining, though. It's worth noting that these transitions aren't going to be suitable for everyone.

[0:57] We can use the media query prefers-reduced-motion to use scroll-behavior: auto. That's how we can use CSS to create animated anchor scrolling that respects users who prefer reduced motion and doesn't annoy users when they're trying to navigate for inline search results.

[1:14] In review, use scroll-behavior: smooth for animated anchor scrolling, but use the focus within pseudo selector, so that it isn't activated when users navigate inline search results. If we are going to use the focus within pseudo selector, we also need to apply a tabindex attribute with a value of -1 to the elements we are going to navigate to.

[1:33] To turn off the rule for those that prefer reduced motion, wrap the rule in a prefers-reduced-motion media query and set the scroll behavior to auto.

Mirha Masala
Mirha Masala
~ 3 years ago

I don't believe focus-within solves much for the inline links. Here's a fork of your Codepen: https://codepen.io/mirhamasala/pen/BadyyZV (The Codepen provided doesn't use inline links, unfortunately). Am I missing something?

Markdown supported.
Become a member to join the discussionEnroll Today