challenges

MDX Table of Contents: Part 6 (Solution)

You can find a summary of the code updates in this pull request .

Step 1: Set scroll-margin-top

We’ll start by adding a scroll-margin-top rule to the .heading class in BlogHeading.module.css. This will keep the heading from hiding under the header, and we can set a value to place the heading 1rem below the header, as specified.

We’ll use the same value we used for the table of contents sticky positioning top in Workshop 3, which made use of the CSS custom property for the height of the header in src/app/globals.css and calc .

BlogHeading.module.css

.heading {
  font-weight: 600;
  line-height: 1.1;
  scroll-margin-top: calc(var(--height-header) + 1rem);
}

Step 2: Add smooth scrolling globally

We can add a rule for smooth scrolling across the entire app in src/app/globals.css. We’ll specify the :root element as the selector, and set scroll-behavior to smooth.

Note: We could add this to the rule for the :root selector at the top of globals.css, but we’re keeping this rule separate because it will soon be surrounded by a media query. 😁

globals.css

:root {
  scroll-behavior: smooth;
}

Step 3: Disable smooth scroll for reduced motion users

Finally, we want to disable the smooth scrolling for users who have ‘prefers-reduced-motion’ set to reduce. From MDN :

The prefers-reduced-motion CSS media feature is used to detect if a user has enabled a setting on their device to minimize the amount of non-essential motion. The setting is used to convey to the browser on the device that the user prefers an interface that removes, reduces, or replaces motion-based animations.

Such animations can trigger discomfort for those with vestibular motion disorders . Animations such as scaling or panning large objects can be vestibular motion triggers.

As mentioned in the quote, we can use a media query to specify that this rule is only for users with preferred-reduced-motion set to no-preference:

globals.css

@media (prefers-reduced-motion: no-preference) {
  :root {
    scroll-behavior: smooth;
  }
}

To check to see that this is working as intended, you can emulate prefers-reduced-motion in Chrome or enable reduced motion for your environment.

 

Congratulations! 🎉 You’ve made it to the end of this series.