Search code examples
htmlanchormarkdownjekyll

Offset page to prevent sticky header from covering auto-generated anchors


I'm using jekyll to generate my pages and as anyone knows that uses jekyll, the anchor tags on h-tags are automatically generated.

Solutions I am not looking for:

  1. Add padding — my h-tags are using margins because I'm a normal person. Also, my sticky header is 50px tall which means that all my h-tags would need a miniumum of 55(ish)px padding. This causes there to be too much spacing.
  2. Create your own anchor in a span tag — this defeats the point of the autogenerated tags and I'm trying to live a D.R.Y. lifestyle.

Summary: I need to offset the anchor's position without changing the location of the h-tag.


If this has already been answered, I apologize for creating a duplicate question. I could not find the answer to this that was not 'solved' with the previous mentioned 'solutions'.


Solution

  • You may want to use the :target pseudo selector, which matches when the hash in the URL and the id of an element are the same. Therefore, the style will only apply to the h-tag which has been navigated to rather than all of them.

    For example, you can use :target::before to add a margin to the top of the selected tag:

    :target::before {
          content: "";
          display: block;
          margin-top: -75px;
          height: 75px;
    }
    

    Here, this technique was used along with an animation which removes the margin after one second so that the margin no longer exists if/when the user scrolls up the page.