DEV Community

Gajus Kuizinas
Gajus Kuizinas

Posted on

Offsetting named anchor and scrollIntoView position.

Named anchor links are used to refer to a section of a HTML page. Target element is identified by giving element id (e.g. <div id='foo' />) and a link to the element is constructed by prefixing the target element ID with an anchor, e.g. <a href='#foo' />. They are great for linking to specific pieces of content on a page, such as comments, products and so forth. Here are some examples:

Notice what is wrong with all of those links?

Bad

The scroll cuts right at the top of the content that is linked. Compare it to:

Alt Text

Isn't nicer when there is a small offset?

([Sigh] This post is when everyone realises that I have an OCD).

The reason it behaves the way it does is because the ID is attached directly to the heading element. This is not required.

It is a small thing, but it grids my gears because the fix is easy:

When you want to create a named anchor, create an auxiliary element with relative position and add anchor link with an offset absolute position. Like this:

<div style='position: relative;'>
  <a name='foo' style='position: absolute; top: -20px;'>  
</div>

Enter fullscreen mode Exit fullscreen mode

This simple markup change allows you to create an arbitrarily offset anchor that is not dictated by padding/ margin or other attribute of the content.

Latest comments (1)

Collapse
 
lobo_tuerto profile image
Víctor Adrián

What happens when you aren't able to easily change the anchors, or the content they point to?

For example for sites written in Markdown, you can get an autogenerated TOC that directly links to the headers.


What I found was a very easy and cool hack. By applying some styling to the header elements you can achieve the desired effect.

Just apply a padding, then subtract the same quantity as a negative margin.

If you want to see it in action, have a look at this: lobotuerto.com/blog/vuejs-componen...

Click around using the TOC or the § symbols besides the headers.

Code is more or less like this:

h1::before, h2::before, h3::before
  content: ''
  display: block
  margin-top: -80px
  padding-top: 80px