如果我在HTML页面中有一个非滚动头,固定在顶部,有一个定义的高度:

是否有一种方法可以使用URL锚(#fragment部分)让浏览器滚动到页面中的某一点,但仍然尊重固定元素的高度,而不需要JavaScript的帮助?

http://example.com/#bar
WRONG (but the common behavior):         CORRECT:
+---------------------------------+      +---------------------------------+
| BAR///////////////////// header |      | //////////////////////// header |
+---------------------------------+      +---------------------------------+
| Here is the rest of the Text    |      | BAR                             |
| ...                             |      |                                 |
| ...                             |      | Here is the rest of the Text    |
| ...                             |      | ...                             |
+---------------------------------+      +---------------------------------+

当前回答

如果你不能或不想设置一个新类,在CSS的:target伪类中添加一个固定高度的::

:target::before {
  content: "";
  display: block;
  height: 60px; /* fixed header height*/
  margin: -60px 0 0; /* negative fixed header height */
}

或者使用jQuery相对于:target滚动页面:

var offset = $(':target').offset();
var scrollto = offset.top - 60; // minus fixed header height
$('html, body').animate({scrollTop:scrollto}, 0);

其他回答

我发现我必须同时使用muttenxd和Badabam的CSS解决方案,因为第一个在Chrome中不起作用,第二个在Firefox中不起作用:

a.anchor { 
  padding-top: 90px;
}

a.anchor:before { 
  display: block;
  content: "";
  height: 90px;
  margin-top: -90px;
}

<a class="anchor" name="shipping"></a><h2>Shipping (United States)</h2>
...

这对我来说很管用:

HTML链接到锚点:

<a href="#security">SECURITY</a>

HTML锚:

<a name="security" class="anchor"></a>

CSS:

.anchor::before {
    content: "";
    display: block;
    margin-top: -50px;
    position: absolute;
}

如果你不能或不想设置一个新类,在CSS的:target伪类中添加一个固定高度的::

:target::before {
  content: "";
  display: block;
  height: 60px; /* fixed header height*/
  margin: -60px 0 0; /* negative fixed header height */
}

或者使用jQuery相对于:target滚动页面:

var offset = $(':target').offset();
var scrollto = offset.top - 60; // minus fixed header height
$('html, body').animate({scrollTop:scrollto}, 0);

我需要一些东西,适用于入站链接,页面上的链接,并可以通过JS的目标,以便页面可以响应头部高度的变化

HTML

<ul>
  <li><a href="#ft_who">Who?</a></li>
  <li><a href="#ft_what">What?</a></li>
  <li><a href="#ft_when">When?</a></li>
</ul>
...
<h2 id="ft_who" class="fragment-target">Who?</h2> 
...
<a href="#">Can I be clicked?</a>
<h2 id="ft_what" class="fragment-target">What?</h2>
...
<h2 id="ft_when" class="fragment-target">When?</h2> 

CSS

.fragment-target {
    display: block;
    margin-top: -HEADER_HEIGHTpx;
    padding-top: HEADER_HEIGHTpx;
    z-index: -1;
}

z-index: -1允许片段目标上方“填充区域”中的链接仍然是可点击的,正如@MuttenXd在他的回答中所评论的那样

我还没有在IE 11、Edge 15+、Chrome 38+、FF 52+或Safari 9.1+中发现问题

官方引导采用答案:

*[id]:before { 
  display: block; 
  content: " "; 
  margin-top: -75px; // Set the Appropriate Height
  height: 75px; // Set the Appropriate Height
  visibility: hidden; 
}

学分