Pure CSS to achieve the internal web anchor jump up and down offset of the sample code


Recently, when I was working on my “football navigation” website, I encountered a need that the anchor point inside the webpage jumps down a little to avoid being covered by the fixed navigation bar at the top.

Some methods are searched on the Internet, most of which are controlled by JS when jumping. Later, I found a method implemented only by CSS on the personal blog of a foreign developer. I felt it was very concise and easily translated his implementation method. Generally, the style of the fixed navigation bar at the top of our webpage is as follows:

<div class="header" style="position: fixed; top: 0;"></div>

Then, there will be a list of a links to jump to:

  <li><a href="#section1">Anchor Text</a></li>
  <li><a href="#section2">Anchor Text</a></li>

The requirement is that when you click each a link above, the page will be positioned to the anchor position of the corresponding ID:

<div class="section" id="section1"></div>
<div class="section" id="section2"></div>

But if there’s one at the top position:fixed When positioning to this anchor, the upper part of the content in the anchor will be covered by the top fixed Div. The solution is to add an empty page anchor in each location content, put the page element ID to jump on the empty element, and set the CSS of the empty element to realize the offset when jumping. We define the empty element as the div whose class is anchor, and set the ID of the div to the ID of the link a above to jump to

<div class="anchor" id="section1"></div>
<div class="section"></div>
<div class="anchor" id="section2"></div>
<div class="section"></div>

The CSS attribute of the empty element is as follows:

  display: block;
  height: 60px; /* Consistent with the height of the top fix*/
  margin-top: -60px; /* Consistent with the height of the top fix*/
  visibility: hidden;

Here, we want to achieve the internal anchor jump function.

In short, the offset value here is the height occupied by the empty element when jumping. Using this space occupying element, we can achieve the offset effect when we need the anchor jump.

So far, this article about the pure CSS implementation of web page internal anchor jump up and down offset sample code is introduced here. For more relevant CSS internal anchor jump up and down offset content, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!