htmlcssanchoroffset

How to apply an offset to a #link on another page


I got a website which basically is 80% index.html plus a few minor subpages. Index.html is divided into few sections. However, the navigation has position:fixed and height of - say - 100px, so links like

<a href="#section">

need a 100px offset. I achieve it through jQuery (ill leave all ifs for specific sections out):

$("#navigation a").click(function() {
    event.preventDefault();
    var offset = $("#section1").offset().top - 100;
    $(window).scrollTop(offset);
}

The problem is that when i navigate to index.html from subpages, this trick won't work, so i must not use this function on subpages and simply "allow default".

Is there a way to navigate to a #section of an other html document with a proper offset (cant be hard coded)?


Solution

  • You can achieve this without Javascript.

    Assumed on the index.html all targets having the class section. With this CSS snippet the fixed navigation does not hide any target.

    body {
       padding-top: 60px;
       margin-top: 0px;
    }
    
     #fixed-nav { 
       position:fixed;
       height:50px;
       line-height:50px;
       vertical-align:middle;    
       background:#000;
       top:0;
       left:0;
       right:0;
       color:#FFF;
       padding-left:5px;
    }
    
    #fixed-nav a {
      color: white;
      margin-right: 10px;
      text-decoration: none;
    }
    
    #sections .section {
      height:400px;
      padding-left:5px;
    }
    
    #sections .section:before { 
      display: block; 
      content: " "; 
      margin-top: -60px; 
      height: 60px; 
      visibility: hidden; 
    <div id="fixed-nav">
       <a href="#target-1">To target 1</a>
       <a href="#target-2">To target 2</a>
       <a href="#target-3">To target 3</a>
       <a href="#target-4">To target 4</a>
       <a href="#target-5">To target 5</a>
    </div>
    
    <div id="sections">
      <div class="section" id="target-1">
        Target 1
      </div>
      <div class="section" id="target-2">
        Target 2
      </div>
      <div class="section" id="target-3">
        Target 3
      </div>
      <div class="section" id="target-4">
        Target 4
      </div>
      <div class="section" id="target-5">
        Target 5
      </div>
    </div>