Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperlink and fragment ID Vertical Offset Problem

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?

like image 346
Lea Hayes Avatar asked Jul 16 '11 02:07

Lea Hayes


2 Answers

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.

like image 139
vinceh Avatar answered Nov 15 '22 20:11

vinceh


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; }

like image 43
dougcosine Avatar answered Nov 15 '22 22:11

dougcosine