In this lesson, we take a look at how you can use CSS scroll-margin-top to give your content breathing room when using anchor scrolling.
Combine this with CSS variables and calc to combat fixed-position nav layouts.
Jhey Tompkins: [0:00] We've got some markup with some anchor tags and some headings, and we can use the anchor tags to navigate to the headings.
[0:06] What you'll notice though is that our heading has no breathing room above it. To combat this, we can use scroll-margin-top and then provide a value. Now, when we use our anchor tag, our content has that little bit of breathing room, defined by scroll-margin-top.
[0:23] What if we have different heading types such as h3 and h4? We could define a list of all the elements that need scroll-margin-top, but what would be neater is to use scroll-margin-top on any element that has an id attribute.
[0:37] One popular layout style is to have a fixed position nav. Let's set position: fixed and give it a border-bottom of 1px, solid white. If we use our anchor tag to scroll to Section Two, we'll see that Section Two is cut off by our new fixed position nav.
[0:54] To combat this, we can use CSS variables. Let's create a variable for the header-height and let's set it to 80px. We can set the height of our nav using that new variable, and then account for it in our scroll-margin-top by using calc, calc(var(--header-height) + 2rem).
[1:14] If we try navigating [inaudible] tag again, we scroll to the section with the breathing room of the header, plus the scroll-margin-top that we defined previously.
[1:24] In review, we can use CSS scroll-margin-top to give our elements a little bit of breathing room when we use anchor scrolling. Instead of listing out all the elements that we need to apply scroll-margin-top to, a neat little trick is to use a selector for an id attribute.
[1:38] If we have a layout with a fixed position nav, we can use CSS variables to combat this by defining a header-height that we can then use in calc, and still give our elements that little bit of breathing room.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!