如果我在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    |
| ...                             |      | ...                             |
+---------------------------------+      +---------------------------------+

当前回答

<div style="position:relative; top:-45px;">
    <a name="fragment"> </a>
</div>

这段代码应该可以达到目的。将标题栏的高度替换为45px。

编辑:如果使用jQuery是一个选项,我也成功地使用jQuery。带有偏移值设置的localScroll。偏移量选项是jQuery的一部分。scrollTo, jQuery。localScroll是在此基础上构建的。这里有一个演示:http://demos.flesler.com/jquery/scrollTo/(第二个窗口,在'offset'下)

其他回答

我发现我必须同时使用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文件中,就可以看到神奇的效果。

对于动态高度和间隙变量

html {   
    --headerHeight:79px;   
    --gap:40px;   
    scroll-padding-top: calc(var(--headerHeight) + var(--gap)); 
}

对于固定间隙值

html { 
    scroll-padding-top: 120px; 
}
<div style="position:relative; top:-45px;">
    <a name="fragment"> </a>
</div>

这段代码应该可以达到目的。将标题栏的高度替换为45px。

编辑:如果使用jQuery是一个选项,我也成功地使用jQuery。带有偏移值设置的localScroll。偏移量选项是jQuery的一部分。scrollTo, jQuery。localScroll是在此基础上构建的。这里有一个演示:http://demos.flesler.com/jquery/scrollTo/(第二个窗口,在'offset'下)

刚刚发现了另一个纯CSS解决方案,对我来说就像一个魅力!

html {
  scroll-padding-top: 80px; /* height of your sticky header */
}

在这个网站上找到!