HTML: Making a link lead to the anchor centered in the middle of the page

Viewed 54018

I have a link to an anchor on my html page. When the link is clicked it causes the page to scroll to the anchor so that the anchor is at the very top of the visible part of the page. How can I make the page scroll so that the anchor will be in the middle of the page?

11 Answers

Extending off of charles.cc.hsu's answer, we can do this for elements of arbitrary height using the vh CSS unit, which is relative to the viewport's height.

HTML:

<span class="anchor" id="section1"></span>
<div class="section"></div>

CSS:

.anchor{
    display: block;
    height: 50vh; /* 50% viewport height */
    margin-top: -50vh;
    visibility: hidden;
}

vh is supported in in IE9 and up, so it's pretty safe to use.

$(window).on("load", function () {
    var urlHash = window.location.href.split("#")[1];
    if (urlHash &&  $('#' + urlHash).length )
          $('html,body').animate({
              scrollTop: $('#' + urlHash).offset().top-100
          }, 1000);
});
Related