Reputation: 381
I'm only asking because the header is fixed to the top of the page and it has a height of 75px, so when I click on a link (<a href="/company/#contact/">contact</a>
) it does got to that section but the top part sits behind the header. Is there anyway to link to the sections and have an offset of 75px above it?
Thanks!
Upvotes: 1
Views: 63
Reputation: 66123
An alternative solution to what others have proposed would be overriding the browser's default behavior of scrolling to the anchors, and substitute that with your own way of calculating the scrolling based on the offset of the target element from the top, i.e. .offset().top
and then subtracting the height of the fixed header element.
Let's say you have the following markup:
<header>
Fixed header.
<a href="#head1">Heading 1</a>
<!-- more headers -->
</header>
<h1 id="head1">Heading 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vel dictum nulla. Pellentesque tincidun</p>
<!-- more content -->
For the JS, it is a bit tricky. First we determine whether the URL contains a hash, if yes, we call the function to reposition the page. Otherwise, we listen to click events triggered from all internal anchors, using the selector a[href^="#"]
. For the function it has to perform this logic:
window.location.hash
, or the href
attribute passed into it).offset().top
.height()
, to account for events where the header height might change or be dynamic — otherwise you can just use 75
).Condensing the points above, we can use the following script:
$(function() {
// Define scroll position modifier
var scrollPos = function(targetID) {
var targetOffset = $(targetID).offset().top;
$(window).scrollTop(targetOffset - $('header').height());
};
// Update scroll position if hash is detected in URL
if(window.location.hash) {
// Use .substring(1) to remove '#' at the front
scrollPos(window.location.hash.substring(1));
}
// Update scroll position when navigated
$('a[href^="#"]').click(function(e) {
// Prevent native scrolling
e.preventDefault();
// Manual scroll position update
scrollPos($(this).attr('href'));
});
});
See fiddle here: http://jsfiddle.net/teddyrised/u11011jc/
Upvotes: 1
Reputation: 5985
When you have an absolutely positioned (or fixed position) header, you need to have some compensation to bring your entire body content down.
You should add a section above your top-most section on your page and give it a height of 75px. This will think the page is 75px lower than it actually is. (I usually call this nav-push
, like it's pushing the content down because of the nav)
Another solution is to give your anchor tag a class and position it relatively, then give it a top offset of 75px
a#contact {
position:relative;
top:-75px;
}
Upvotes: 0
Reputation: 1639
You could use jquery:
$(function() {
$('html, body').animate({
scrollTop: "75px"
}, 2000);
});
Here is a jsfiddle example:
Upvotes: 0