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:
- https://dev.to/gajus/dynamically-generating-sql-queries-using-node-js-2c1g#binding-a-list-of-values
- https://github.com/gajus/slonik#contents
- https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
Notice what is wrong with all of those links?
The scroll cuts right at the top of the content that is linked. Compare it to:
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>
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.