【问题标题】:Fixed nav and anchor offset issue修复了导航和锚点偏移问题
【发布时间】:2019-07-03 21:43:45
【问题描述】:

给定一个固定的导航和一些带有锚点的部分;单击哈希链接时 - 固定导航与部分锚点重叠。

我看过一些类似的帖子,但似乎找不到适合我的特定情况的解决方案。

由于项目限制,我无法覆盖 .anchor 样式或使用 JavaScript 修复该偏移或 add any additional HTML elements

虽然我可以在.anchor - the hack with a height and a negative margin 中添加一个伪元素来平衡它,但在我的情况下不起作用,因为.anchor 具有顶部填充和边框。

<h3 class="anchor" id="section-1">Title 1</h3>
<p>Description 1</p>

<h3 class="anchor" id="section-2">Title 2</h3>
<p>Description 2</p>

<h3 class="anchor" id="section-3">Title 3</h3>
<p>Description 3</p>
.nav {
    position: sticky;
}
.anchor {
    border-top: 1px solid #333940;
    margin-top: 2rem;
    padding-top: 2rem;
}
.anchor::before {
}

谁能帮我弄清楚是否有纯 CSS 方式来修复锚点的偏移量?

【问题讨论】:

    标签: html css


    【解决方案1】:

    试试这个。

    <script type="text/javascript">
    $('a[href^="#"]').on('click',function (e) {
    // e.preventDefault();
    
      var target = this.hash,
      $target = $(target);
    
      $('html, body').stop().animate({
       'scrollTop': $target.offset().top-80
      }, 1000, 'swing', function () {
       window.location.hash = target;
      });
    });
    

    top-80 是你想要的空间高度

    【讨论】:

    • 感谢您的回答!是的,我也知道这一点,但正如我所提到的 - 由于项目要求,我无法使用 JavaScript(或 jQuery),并且正在寻找纯 CSS 解决方案(如果存在)。
    • 是的,我也是mentioned in the description - 我知道这种技术,它只有在没有填充或边框添加到锚点时才有效。但在我的情况下,我有填充和边框,我无法删除,它不适用于它。
    猜你喜欢
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 2016-05-22
    • 2015-12-10
    相关资源
    最近更新 更多