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

当前回答

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

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

对于css,你有:

.paddingtop { 
   padding-top: 90px; 
}

其他回答

你可以用jQuery做到这一点:

var offset = $('.target').offset();
var scrollto = offset.top - 50; // fixed_top_bar_height = 50px
$('html, body').animate({scrollTop:scrollto}, 0);

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

从2021年4月起,有一个非黑客的、完全跨浏览器的解决方案:

h1 {
  scroll-margin-top: 50px
}

它是CSS Scroll Snap规范的一部分。可以在所有现代浏览器上运行。(更多信息,请参阅MDN页面关于scroll-margin-top, scroll-padding-top)

我使用这种方法:

/* add class="jumptarget" to all targets. */

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

它在每个目标之前添加一个隐形元素。支持IE8+。

这里有更多的解决方案: http://nicolasgallagher.com/jump-links-and-viewport-positioning/

我没有看到简单地使用:target作为一个选项列出。我发现

:目标{margin-top: -100px;padding-top: 100 px;}

似乎在提供的场景中工作。:target也兼容所有现代浏览器。https://caniuse.com/?search=%3Atarget