Search code examples
htmlcss

offset scroll to in html?


I am trying to do the thing in html where you click on a link and it automatically scrolls to where you want in the page. Here is the button/link part of the code:

<li><a href="#Origins">Origins</a></li>

And then I have it link to this part of the page represented by this code:

<h3 id="Origins">Origins</h3>

This works perfectly fine, however, my header of the page at the top, which is h1, is set to fixed position. So when you click the link, it goes too far down to where the header at the top is covering the "origins" part of the page. I tried adding padding to the top of origins which works but then there is a lot of blank space above "origins" in the page which I do not want. Does anyone have any ideas? Thanks in advance!


Solution

  • You could do it with Javascript(example below requires jQuery, but could also be accomplished with Vanilla Javascript) by scrolling to the position of the h3 minus the height of the h1:

    $(function() {
      var h1Height = $('h1').height(); // get height of h1 tag
      $('li a').click(function (e) {
          e.preventDefault();
          var target = $(this.hash);
          $('html, body').animate({
              scrollTop: target.offset().top - h1Height // scroll to h3 minus height of h1
          }, 1000);
          return false;
      });
    });
    body,html {
      margin:0;
      padding:0;
    }
    h1{
      margin:0;
      padding:0;
      width:100%;
      background:#fff;
      position:fixed;
      top:0;
    }
    ul {
      margin:60px 0 0;
    }
    .space, h3 {
      margin:1000px 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h1>Heading</h1>
    
    <ul><li><a href="#Origins">Origins</a></li></ul>
    
    <div class="space"></div>
    
    <h3 id="Origins">Origins</h3>