如果我在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和HTML,使用上面提到的“锚:之前”方法。我认为它是最好的,因为它不会在你的divs之间产生大量的填充。

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

这似乎并不适用于页面上的第一个div,但你可以通过添加填充到第一个div。

#anchor-one{padding-top: 60px;}

这里有一个工作小提琴:http://jsfiddle.net/FRpHE/24/

其他回答

使用这个脚本

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top -140
    }, 1000);
});

我认为这种方法更有用:

<h2 id=“bar” title=“Bar”>Bar</h2>

[id]:target {
    display: block;
    position: relative;
    top: -120px;
    visibility: hidden;
}

[id]:target::before {
    content: attr(title);
    top: 120px;
    position: relative;
    visibility: visible;
}

我已经很容易地使用CSS和HTML,使用上面提到的“锚:之前”方法。我认为它是最好的,因为它不会在你的divs之间产生大量的填充。

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

这似乎并不适用于页面上的第一个div,但你可以通过添加填充到第一个div。

#anchor-one{padding-top: 60px;}

这里有一个工作小提琴:http://jsfiddle.net/FRpHE/24/

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

来自:https://css-tricks.com/fixed-headers-on-page-links-and-overlapping-content-oh-my/

通过添加滚动填充顶部属性来解决这个问题,只需将此代码添加到您的CSS文件中,就可以看到神奇的效果。

对于动态高度和间隙变量

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

对于固定间隙值

html { 
    scroll-padding-top: 120px; 
}