Offset Anchor Tag

Working with CSS fixed headers and HTML anchor tags can be a little tricky. The jump point will need to be offset by the height of the header, and other fixed elements.

Anchor Tag

<a class="anchor_tag"></a>

CSS Offset (hidden content)

.anchor_tag {
    display: block;
    position: relative;
    top: -5em;
    visibility: hidden;
}

Source.

jQuery Offset (visible content)

(function(jQuery, window) {
var adjustAnchor = function() {

var jQueryanchor = jQuery(':target'),
fixedElementHeight = 200;

if (jQueryanchor.length > 0) {

window.scrollTo(0, jQueryanchor.offset().top - fixedElementHeight);

}

};

jQuery(window).on('hashchange load', function() {
adjustAnchor();
});

})(jQuery, window);

Source.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.