Fixed Header page with Anchor points

Whilst designing the new Techbytes site I came a cross a problem. The fixed header which contains the Nav menu and logo stays in the same place (fixed positioning) whilst the rest of the page scrolls. This is great for content, and with a transparent’ish header looks great too.

But using Anchor point “a href” tags throughout the info page meant that the content jumped to a point that was at the top of the page, BEHIND the header. Which looks rubbish is tough to read. It also breaks the web design rule number 1, Make things easy for people regardless of how complicated your design, otherwise they will just go somewhere else.

So here’s my solution adapted from the very brilliant guys at PixelFlips blog.

The Original Setup

The Header

<div style="position:fixed; top:0;  left:0; width:100%; height:100px; background: rgba(0,0,0,0.5)"></div>

The Links

<a href="#paragraph-1">Paragraph 1 Title</a>
<a href="#paragraph-2">Paragraph 2 Title</a>
<a href="#paragraph-3">Paragraph 3 Title</a>

The Anchors

<a name="paragraph1"></a>
Paragraph text blah blah blah
<a name="paragraph2"></a>
Paragraph text blah blah blah
<a name="paragraph3"></a>
Paragraph text blah blah blah/code>

This original setup caused the problem of jumping to the top of the page, what we really need is some general CSS rule for anchors only that we can apply a height to, which offsets the height of the header and jumps the top of the content a bit lower.

The Fix

So the fix,takes the place of <a name> and keeping everything else the same except we add in that general CSS class which we’ll name “anchor” in the form of an <a span class=””> and simply add an ID id=”paragraph1″. So the full line becomes

<a span class="anchor" id="paragraph1"></a>
Paragraph text blah blah blah

The Magical CSS that actually fixes the problem (usually described in an external stylesheet)

display: block;
height: 100px;
margin-top: -100px;
visibility: hidden;

The height attribute here should be set to whatever you header height is, so in this case 100px. The margin-top then pops it back up so not every anchor point has a massive gap between it. The visibility:hidden is purely for neatness.

Enjoy 🙂 and please comment if it brings you success and prosperity.

No comments yet.

Leave a Reply