Add scroll margin to all elements which can be targeted

Categories

We can add an extra bit of space to targeted elements, thanks to modern CSS!


You can target an element with HTML by giving it an id then in the URL bar, adding a reference to that id, prefixed with a #, like so:

Code language
HTML
<h2 id="my-lovely-heading">Hello</h2>
Code language
text
https://example.com/#my-lovely-heading

With this set up, the browser will automatically scroll the user to that targeted element. It’s why you often find this pattern in long-form writing, such as on this site. What’s been problematic in the past though, is that targeted element will be flush to the top of the viewport when the browser has finished scrolling—not ideal.

Luckily, CSS has our back with scroll-margin-top. A pro tip is to add this to all elements with an id in your project.

Code language
CSS
[id] {
  scroll-margin-top: 2ex;
}

The extra fancy part is by using 2ex, we use the x-height of the chosen font and its size, twice. Handy! You can read more about these sort of units, here.

An extra bonus pro tip is to style the targeted element with the :target pseudo-class and use some native smooth scrolling, just like I did in the below demo 👇

Demo


Comments

If you liked this post, you might like these ones, too

  1. CSS Frameworks, hype and dogmatism

    Some notes on the dogmatism and gatekeeping themes of Tech Twitter and how they can generate often incorrect and naive statements—specifically about frameworks and methodologies.

    Continue
  2. Prevent squishy elements with flex none

    You can prevent that annoying squished look that elements like icons get when space runs out in a flex context with flex: none.

    Continue
  3. Flow CSS Utility

    🔥 A handy quick tip.

    Continue

Become a supporter by joining the Piccalilli Membership

For $5 per month, you get access to a private, friendly Discord community, a regular newsletter, huge discounts on courses and free access to all premium tutorials.

Most importantly, by becoming a supporter, you help make as much content, free-to-everyone as possible on this site, which benefits everyone. As a member, you also get an ad-free experience around the site.

Support Piccalilli by becoming a member

Sign up for updates

Stay up to date with updates from Piccalilli. You’ll get alerted as soon as any new content gets published. You’ll also get updates on upcoming courses and membership features! You can unsubscribe at any time, too.