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

当前回答

你现在可以使用scroll-margin-top,它被广泛采用。

只需将以下CSS添加到你想要滚动到的元素:

.element {
  scroll-margin-top: 2em;
}

其他回答

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

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

你现在可以使用scroll-margin-top,它被广泛采用。

只需将以下CSS添加到你想要滚动到的元素:

.element {
  scroll-margin-top: 2em;
}

如果你不能或不想设置一个新类,在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);

我认为这种方法更有用:

<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;
}

添加一个带有“paddingtop”的类,这样它就可以工作了;)

<h1><a class="paddingtop">Bar</a></h1>

对于css,你有:

.paddingtop { 
   padding-top: 90px; 
}