Offsetting named anchor and scrollIntoView position.

Gajus Kuizinas - Sep 9 '19 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player