ngungo
ngungo

Reputation: 5322

HTML anchor, but not exact at anchor point

When I want to refer to some part of a webpage with the "http://example.com/#foo"-method, I do:

<h1 id="foo">Foo Title</h1>

But the idea is I need to go above or beyond that anchor by some distance in pixels, for example:

"http://example.com/#foo-100px" 
   or
"http://example.com/#foo+100px"

I've been thinking about this overnight, haven't got any idea how to do that. Thanks in advance for any input.

Upvotes: 2

Views: 1146

Answers (2)

isherwood
isherwood

Reputation: 61083

If you can use a separate anchor instead of your heading as the link target, you can use negative margins to accomplish this without affecting the rest of your layout.

#myAnchor {
    margin-top: -100px;
    margin-bottom: 100px;
    display: block;
    height: 0;
}

<p>My paragraph.</p>
<a name="myAnchor" id="myAnchor"></a>
<h1 id="myHeading">My heading</h1>

Demo

Upvotes: 1

Christopher Esbrandt
Christopher Esbrandt

Reputation: 1198

There is no avoiding using a scripting language for this, at least, not that I know of. Here's a simple jQuery solution: http://code-tricks.com/offset-scroll-to-anchor-tag-with-jquery/

$(function(){
 $("[href^='#']").not("[href~='#']").click(function(evt){
  evt.preventDefault();
  var obj = $(this),
  getHref = obj.attr("href").split("#")[1],
  offsetSize = 145;
  $(window).scrollTop($("[name*='"+getHref+"']").offset().top - offsetSize);
 });
});

JSFiddle: http://jsfiddle.net/vg0x45gy/

Set the offsetSize variable to how many pixels you want it offset by. Use a positive value for above the anchor point and a negative value for below it.

Upvotes: 0

Related Questions