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.
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
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.
上一篇: 任何不开始使用HTML 5文档的理由?
下一篇: HTML锚点,但不是精确的锚点