CSS: How to jump to a differing anchor-position (vertical offset)


jump-anchor-offset - illustration / image by T.Bortels/cpu20.com

The initial question was: how to jump to an anchor, but have a vertical offset of x pixels?

Anchors are somthing like reptiles of webdesign – they are basically dinosaurs, but they’re still here. And they are here for a good reason: anchor links are easy to use and they do their job. You just click on an anchor link, and the page jumps right to the paragraph.

With the rise of one-page-layouts anchor links are becoming even more and more popular these days. There are lots of websites built on the concept of having anchors doing the navigation. When the website consists of only one page, there are not so many options left to actually navigate the page.

But often anchors are just a bit too accurate. When placed at the very beginning of a paragraph or a section or a headline, the jump will lead right to the very beginning of that paragraph or section or headline. This can lead to the odd situation that the detail you wanted to have in focus is actually at the top border of the browser’s viewport.

With the help of a little css magic a vertical offset can be added to an anchor. The actual anchor will then be placed x pixels above its actual position. To get this working the anchor element has to be positioned on an absolute position (position: absolute;) inside the element that you want to target. Here the sample code:

<div style="position:relative;">
    <div class="anchor" id="jump123" style="position:absolute; top:-100px;"></div>
    <div class = "mein_text">I should be 100px below where I currently am!</div>

Anchor offset in jQuery Masonry

Originally I needed this anchor-jump for a good old image gallery, that was organized by the jQuery plugin Masonry. The good news is, that the above trick actually does work well with jQuery Masonry. You just have to place the anchor inside an (invisible) div-element, that is inside the actual image container. Then you can move the position of the anchor outside the container for example by 100 pixels, as it is described in the above code snippet. This will then again bring the targeted image further down towards the center of the screen – the center of attention.


Leave a Reply

Your email address will not be published. Required fields are marked *