The Code of No-Code

Jul 20 2014

Getting "named links" (sometimes called "deep links") working on a page with a fixed header is pretty straight forward. The key is in moving the links up the page the same amount as the height of the header. In this case you have to make sure your links are not wrapping anything:

<a name="section" class="offset"></a>
<h1>Section</h1>

Then in the css for the class offset:

.offset {
  display: block;
  visibility: hidden;
  position: relative;
  top: -75px;
}

So, in the following example page we have several sections. Each with named links and two without the class offset.

The full css for the header and body:

body {
  padding-top: 75px;
}

#fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 75px;
  border: 2px solid black;
  font-size: 30px;
  text-align: center;
  background: #aeeeee;
}

And the html without all the ipsum:

<!DOCTYPE html>
<html>
  <head>
    <title>Fixed Header Example</title>
    <link href="example.css" rel="stylesheet" type="text/css"></link>
  </head>
  <body>
    <div id="fixed-header">
      Fixed Header
    </div>
    <a name="section-one"></a>
    <h1>Section One</h1>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <a name="section-two" class="offset"></a>
    <h1>Section Two</h1>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <a name="section-three"></a>
    <h1>Section Three</h1>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <a name="section-four" class="offset"></a>
    <h1>Section Four</h1>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
  </body>
</html>