Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add padding-top to scroll when using href="#id"

I have an anchor tag as follows:

<a href="#map_4D85448A3D4C4180A02BD6FC387ABC45" onclick="jumptosection('map_4D85448A3D4C4180A02BD6FC387ABC45');">A Guide</a>

It navigates to a section that has the id 'map_4D85448A3D4C4180A02BD6FC387ABC45'. The jumptosection function is as follows:

function jumptosection(id) {
    var target = document.getElementById(id);
    if(document.all){
        document.documentElement.scrollTop = target.offsetTop;
    }else{
        var top = 0;
        do {
            top += target.offsetTop  || 0;
            target = target.offsetParent;
        } while(target);

        document.body.scrollTop = top ;
    }
    //$('#article').css.paddingTop = '55px';
    return false;

But even if I write nothing in this function, the behaviour is still the same. The problem is that I have a header strip of 92px that hides some part of the section when I click on the given anchor. How do I make it scroll to the given section while adding some pixels to escape the header?

like image 737
CodingIsComplex Avatar asked Nov 29 '22 00:11

CodingIsComplex


2 Answers

While the chosen answer serves the purpose, we now have explicit CSS property for this, called scroll-margin.

Basically, you avoid any trickery by adding unnecessary elements - this margin is just calculated when you navigate via anchor tag (or if you have set up native css scroll snapping - https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scroll_Snap/Basic_concepts).

Using this with CSS variables is really useful. Here's an example if you have a fixed / sticky header:

/* Set the header variable */

--h-header: 50px;

/* Set the scroll margin top on all anchor elements by using .anchor class */
/* Note: I'm setting plus 2.5em so the element has some breathing room on the top */

.anchor {
    scroll-margin-top: calc(var(--h-header) + 2.5em);
}

MDN Docs: https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin

CSS-Tricks guide: https://css-tricks.com/almanac/properties/s/scroll-margin/

like image 176
tomijovanoski Avatar answered Dec 09 '22 20:12

tomijovanoski


It is possible. I would do it without javascript, so it works for all. Even no changes on you JS are needed.

You just need to create an empty element above the element you want to scroll to. The CSS does the magic. It creates a hidden box in the height of you offset:

HTML:

<span class="anchor" id="map_4D85448A3D4C4180A02BD6FC387ABC45"></span>
<h1>Element to scroll to</h1>

CSS:

.anchor {
    display: block;
    height: 92px;
    margin-top: -92px;
    visibility: hidden;
}

See a working demo here: https://jsfiddle.net/eczxm1rs/1/

like image 44
eisbehr Avatar answered Dec 09 '22 18:12

eisbehr