NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Paramétrer des anchors - Entête en position sticky ou fixed
Intermediate
Web Hosting Canada

Last modified : Aug 23 2022

Estimated reading time : 3 minutes, 42 seconds - 275 words

With this tutorial, we will show you how to configure anchors at the perfect height with either position sticky or fixed.

We found various ways to pull this off with CSS but we also found additional coding information on the web.

The first thing required is that your fixed or sticky header needs to be measured in pixels to get an approximate height of your header.

Result of anchors with a fixed header.

We can clearly see in our example that the title is in the anchor. Logically, seeing as my ID is above it, we should land above the title.

Paramétrer des anchors – Entête sticky ou fixed

CSS for your sticky or fixed header

You need to make sure to add the following CSS value: top:0. It’s this value that will position perfectly your anchor at the right spot.

The problem with headers configured with a sticky or fixed position is that the anchor doesn’t always land where you want it to be given there’s a gap caused by the pixel height of the header.

Here our HTML body needs to have the sticky CSS while the header needs position and top.

body.stiky header {
  position: sticky;
  background: #fff;
  z-index: 3;
  width: 100%;
  left: 0;
  top: 0;
}

We then found this helpful code which will fix the gap issue.

In our example, the height of our header is 215px.
OFFSET_HEIGHT_PX: 215,

Javascript to add in the footer

<script>
(function(document, history, location) {
  var HISTORY_SUPPORT = !!(history && history.pushState);

  var anchorScrolls = {
    ANCHOR_REGEX: /^#[^ ]+$/,
    OFFSET_HEIGHT_PX: 215,

    /**
     * Establish events, and fix initial scroll position if a hash is provided.
     */
    init: function() {
      this.scrollToCurrent();
      $(window).on('hashchange', $.proxy(this, 'scrollToCurrent'));
      $('body').on('click', 'a', $.proxy(this, 'delegateAnchors'));
    },

    /**
     * Return the offset amount to deduct from the normal scroll position.
     * Modify as appropriate to allow for dynamic calculations
     */
    getFixedOffset: function() {
      return this.OFFSET_HEIGHT_PX;
    },

    /**
     * If the provided href is an anchor which resolves to an element on the
     * page, scroll to it.
     * @param  {String} href
     * @return {Boolean} - Was the href an anchor.
     */
    scrollIfAnchor: function(href, pushToHistory) {
      var match, anchorOffset;

      if(!this.ANCHOR_REGEX.test(href)) {
        return false;
      }

      match = document.getElementById(href.slice(1));

      if(match) {
        anchorOffset = $(match).offset().top - this.getFixedOffset();
        $('html, body').animate({ scrollTop: anchorOffset});

        // Add the state to history as-per normal anchor links
        if(HISTORY_SUPPORT && pushToHistory) {
          history.pushState({}, document.title, location.pathname + href);
        }
      }

      return !!match;
    },
    
    /**
     * Attempt to scroll to the current location's hash.
     */
    scrollToCurrent: function(e) { 
      if(this.scrollIfAnchor(window.location.hash) && e) {
      	e.preventDefault();
      }
    },

    /**
     * If the click event's target was an anchor, fix the scroll position.
     */
    delegateAnchors: function(e) {
      var elem = e.target;

      if(this.scrollIfAnchor(elem.getAttribute('href'), true)) {
        e.preventDefault();
      }
    }
  };

	$(document).ready($.proxy(anchorScrolls, 'init'));
})(window.document, window.history, window.location);
</script>

Final result with the anchor

We see that the anchor is positioned exactly where the ID is, i.e. above the title.

Avec le code

Slide effect on the anchor

You can also add a slide effect that drops the ID towards the anchor.

html {scroll-behavior: smooth;}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>