Fix anchor links hidden by top navigation

A common issue with anchor links on webpages is that when the page jumps to the anchor, the top navigation bar covers part of the content (usually the header or the exact spot that the anchor is tied to). There are multiple ways to solve this problem depending on how you create and format your anchor tags. Here, we outline some of the solutions which have worked for us.

Use CSS-only solution for empty anchor tags

If you are adding anchor tags before elements (they are not surrounding the elements), you can use a CSS-only solution to make sure that the anchor jumps to the correct position on the page.

  1. Go to Settings > Style.
  2. Below the Preview Pane, be sure Custom CSS is selected
  3. Copy the code below and paste it into the Custom CSS editor.
    .hg-article-body a:not([href]) {
      display: block;
      position: relative;
      top: -140px; 
      visibility: hidden;
    }
  4. You can increase or decrease the top: "-140px" in row 4 to change where the page jumps.
  5. Be sure to Save your changes.
If you use this solution and your anchor tags are actually surrounding your elements, it will cause the elements to be invisible. Use the JavaScript solution below instead.

Use JavaScript solution for anchor tags wrapping elements

If your anchors tags wrap around your elements, you can use a JavaScript solution to make sure the anchors display on the correct position of the page. 

  1. Go to Settings > Style.
  2. Below the Preview Pane, be sure that Custom HTML is selected.
  3. In the Custom HTML dropdown, select Body.
  4. Copy the code below and paste it into the bottom of the Body Custom HTML editor.
    <script>
    // The function actually applying the offset
    function offsetAnchor() {
    if (location.hash.length !== 0) {
    window.scrollTo(window.scrollX, window.scrollY - 100);
    }
    }
    
    // Captures click events of all <a> elements with href starting with #
    $(document).on('click', 'a[href^="#"]', function(event) {
    // Click events are captured before hashchanges. Timeout
    // causes offsetAnchor to be called after the page jump.
    window.setTimeout(function() {
    offsetAnchor();
    }, 0);
    });
    
    // Set the offset when entering page with hash present in the url
    window.setTimeout(offsetAnchor, 0);
    </script>
  5. Increase or decrease the "100" in row 5 to change where the page jumps.

  6. Be sure to Save your changes.

This solution was found on StackOverflow.