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

当前回答

上面的答案创建了一个60px高的标签,屏蔽了其他因此停止工作的链接。我发现这个方法没有副作用。

<a class="anchor" id="top"></a>

a.anchor {
    display: block;
    position: relative;
    top: -60px;
    visibility: hidden;
}

其他回答

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

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

在这个网站上找到!

官方引导采用答案:

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

学分

我也有同样的问题。 我通过向锚元素添加一个类来解决这个问题,并将topbar高度作为padding-top值。

<h1><a class="anchor" name="barlink">Bar</a></h1>

我使用这样的CSS:

.anchor { padding-top: 90px; }

使用:before实现的效果很好,直到我们意识到伪元素实际上覆盖和阻塞了伪元素区域内的指针事件。使用类似pointer-events: none的东西在:before上甚至直接在锚上都没有影响。

我们最终所做的是使锚的定位是绝对的,然后调整它的位置为偏移/高度的固定区域。

偏移锚没有阻塞指针事件

.section-marker {

    position: absolute;
    top: -300px;
}

这里的值是我们不会阻塞300px范围内的任何元素。缺点是,从Javascript中获取元素的位置需要考虑偏移量,因此任何逻辑都必须进行调整。

我发现处理这个问题的最好方法是(用固定的元素高度替换65px):

div:target {
  padding-top: 65px; 
  margin-top: -65px;
}

如果你不喜欢使用目标选择器,你也可以这样做:

.my-target {
    padding-top: 65px;
    margin-top: -65px;
}

注意:如果目标元素的背景色与父元素的背景色不同,这个例子将不起作用。 例如:

<div style="background-color:red;height:100px;"></div>
<div class="my-target" style="background-color:green;height:100px;"></div>

在这种情况下,我的目标元素的绿色将覆盖65px的父元素红色。 我没有找到任何纯CSS解决方案来处理这个问题,但如果你没有另一个背景色,这个解决方案是最好的。