小编典典

固定页眉在页定位中重叠

html

如果我在HTML页面中有一个非滚动标题,该标题固定在顶部并具有定义的高度:

有没有一种方法可以使用URL锚点(该#fragment部分)使浏览器滚动到页面中的某个点,但是在 没有JavaScript的帮助下
仍然可以尊重固定元素的高度?

http://foo.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    |
| ...                             |      | ...                             |
+---------------------------------+      +---------------------------------+

阅读 577

收藏
2020-05-10

共2个答案

小编典典

我有同样的问题。我通过将一个类添加到锚元素(顶部栏高度为padding-top值)来解决此问题。

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

然后简单的CSS:

.anchor { padding-top: 90px; }
2020-05-10
小编典典

如果您不能或不想设置一个新类,请在CSS ::before:target伪类中添加一个固定高度的伪元素:

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

或者:target使用jQuery 相对于页面滚动:

var offset = $(':target').offset();
var scrollto = offset.top - 60; // minus fixed header height
$('html, body').animate({scrollTop:scrollto}, 0);
2020-05-14