Named anchor links are used to refer to a section of a HTML page. Target element is identified by giving element
<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?
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.
Top comments (1)
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: