CodingIsComplex CodingIsComplex - 1 year ago 126
CSS Question

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);
document.documentElement.scrollTop = target.offsetTop;
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?

Answer Source

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:


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


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

See a working demo here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download