offsetting an html anchor to adjust for fixed head

2018-12-31 03:47发布

This question already has an answer here:

I am trying to clean up the way my anchors work. I have a header that is fixed to the top of the page, so when you link to an anchor elsewhere in the page, the page jumps so the anchor is at the top of the page, leaving the content behind the fixed header (I hope that makes sense). I need a way to offset the anchor by the 25px from the height of the header. I would prefer HTML or CSS, but Javascript would be acceptable as well.

28条回答
柔情千种
2楼-- · 2018-12-31 04:21

Pure css solution inspired by Alexander Savin:

a[name] {
  padding-top: 40px;
  margin-top: -40px;
  display: inline-block; /* required for webkit browsers */
}

Optionally you may want to add the following if the target is still off the screen:

  vertical-align: top;
查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 04:22

You can achieve this without an ID using the a[name]:not([href]) css selector. This simply looks for links with a name and no href e.g. <a name="anc1"></a>

An example rule might be:

a[name]:not([href]){
    display: block;    
    position: relative;     
    top: -100px;
    visibility: hidden;
}
查看更多
不再属于我。
4楼-- · 2018-12-31 04:23

I found this solution:

<a name="myanchor">
    <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</a>

This doesn't create any gap in the content and anchor links works really nice.

查看更多
余生请多指教
5楼-- · 2018-12-31 04:23

FWIW this worked for me:

*[id]:before { 
  display: block; 
  content: " "; 
  margin-top: -75px; 
  height: 75px; 
  visibility: hidden; 
}
查看更多
若你有天会懂
6楼-- · 2018-12-31 04:23

You can do it without js and without altering html. It´s css-only.

a[id]:before {
    content:"";
    display:block;
    height:50px;
    margin:-30px 0 0;
}

That will append a pseudo-element before every a-tag with an id. Adjust values to match the height of your header.

查看更多
刘海飞了
7楼-- · 2018-12-31 04:23

For the same issue, I used an easy solution : put a padding-top of 40px on each anchor.

查看更多
登录 后发表回答