At the top of my page is an statically positioned menu strip which follows screen during scrolling.
When using fragment linking the scroll position needs to be offset by the height of the menu strip. How can this be achieved?
<a href="#fragment">Go to fragment</a>
<div id="fragment">...</div>
html { padding-top: 38px; } /* Offset page to allow for menu strip */
.menu-strip { position: fixed; top: 0; right: 0; left: 0; height: 38px; }
Is there a simple CSS change that can be made to achieve this?
Otherwise, is there a generic way to offset scrolling by 200px when a fragment is specified?
What you want to do is make handle your own hash linking. A good idea is to group all of your a
that do hash linking. For example
$(".ahashlink").click( function() {
var location = $(this).attr("href");
var offset = $(location).offset().top;
$("body").scrollTop(offset+38);
return false;
});
This will scroll to the correct place PLUS 38 more pixels (the height of your top bar). This, however, will not change your URL in your browser to contain the right hash. This is because once you have window.location.hash = "#something"
then your window will automatically scroll to that hash. So keep that in mind.
This old article has an HTML+CSS only solution.
The basic idea is to use the :before css selector to insert some hidden content before each linkable element to offset them:
<linked_elements>:before {
display: block;
content:" ";
margin-top: -<offset>;
height: <offset>;
visibility: hidden;
}
Here's a jsfiddle of their demo.
This will also (I think) remove the need for html { padding-top: 38px; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With