Offset anchor for fixed header, but keep perma link intact

Added some code to my WordPress to make it add anchor links to all h2 headlines. Furthermore, it is showing a small chain logo in front of each headline, when it is hovered.

This is how it looks like:

Read More

Normal headline

Hovered headline

This is my HTML markup:

<h2 id="contact">
  <a class="anchor" href="#contact">
    <i class="fa fa-link" title="Permalink"></i>
  </a>
  Contact us
</h2>

And this is the CSS:

h2 a.anchor {
  position: absolute;
  top: 0;
  left: 0;
  margin-left: -25px;
  padding: 0.75em 8px 0.75em 4px;    
  font-size: 18px;
  font-size: 1rem;
  line-height: 1;
  color: #CCCCCC;
  display: none;
}

h2:hover a.anchor {
  display: block;
}

However, my page does have a fixed navigation header, so the anchor link needs a little offset. Otherwise, my text content is hidden beneath the fixed header.

I added this code, to achieve the offset:

h2:before {
  display: block;
  content: " ";
  height: 125px;
  margin-top: -125px;
  visibility: hidden;
}

Unfortunately, the chain logo moves up now and is shown 125px above its original position. How can I get both, the chain logo in front of the headline and the 125px offset to cope with the fixed header?

My implementation is losely based on this article, which unfortunately is down today.

Related posts

1 comment

  1. This should work for you.

    (Demo)

    HTML

    <div class="anchor-wrapper" id="contact">
        <h2>
            <a class="anchor" href="#contact">
                <i class="fa fa-link" title="Permalink"></i>
            </a>
            Contact us
        </h2>
    </div>
    

    CSS

    h2 {
        margin: 0px;
        padding: 0px;
    }
    a.anchor {
        font-size: 18px;
        color: #CCCCCC;
        opacity: 0;
        margin-left: -1.2em;
        width: 1em;
    }
    h2:hover a.anchor {
        opacity: 1;
    }
    .anchor-wrapper:before {
        display: block;
        content:" ";
        height: 125px;
        margin-top: -125px;
    }
    

Comments are closed.