How to apply an offset to a #link on another page
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)?
1 Answer
1
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>
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
thanks a lot, and sorry for late thanks:)
– DuchSuvaa
Oct 24 '18 at 13:56