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 👇

Hello, I’m Andy and I’ll help you to level up your front-end development skills.

I'm a designer and front-end developer who has worked in the design and web industries for over 15 years, and in that time, I have worked with some of the largest organisations in the world, like Google, Harley-Davidson, BSkyB, Unilever, The Natural History Museum, Oracle, Capita, Vice Media and the NHS.

On Piccalilli, I share my knowledge and experience to make you a better front-end developer.

I'm the founder of Set Studio, a creative agency that specialises in building stunning websites that work for everyone. Check out what we're all about.