使用Bootstrap 4固定的导航栏在HTML中偏移滚动锚点 [英] Offset scroll anchor in HTML with Bootstrap 4 fixed navbar

查看:158
本文介绍了使用Bootstrap 4固定的导航栏在HTML中偏移滚动锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个由几个部分组成的页面.用户可以通过滚动自己或单击导航栏(带有锚点的href)来转到这些部分.由于Bootstrap 4导航栏固定在顶部,因此将内容放置在其下方.有没有一种方法可以使锚点偏移-54像素,以便每当我单击锚点链接时,它将在导航栏(X:54px)下方而不是导航栏(X:0px)下方显示内容.

So, I have this single page that consists of a few sections. Users can go to these sections by scrolling themselves or clicking in the navbar (a href with anchor). Due to the Bootstrap 4 navbar being fixed to the top, the content gets placed under it. Is there a way I could offset anchors by -54px, so that whenever I click on an anchor link, it would show the content below the navbar (X:54px) and not under the navbar (X:0px).

制作此Codepen以显示我面临的问题:
https://codepen.io/anon/pen/XEjaKv
每当您单击锚点链接时,它将带您到该部分,但是导航栏将覆盖文本.

Made this codepen to show the problem I'm facing:
https://codepen.io/anon/pen/XEjaKv
Whenever you click an anchor link, it will take you to the section, however, the navbar is covering the text..

所有部分的观看高度均为100.

All sections are 100 viewheight.

使用的SCSS:

.container{
  section{
    height: 100vh;
    &#section1{
      margin-top: 54px; // we need to offset the first section by 54px because of the navbar..
    }
    &#section1, &#section3{
      background-color: #ddd;
    }
    &#section2, &#section4{
      background-color:#ccc;
    }
  }
}
html{
  scroll-behavior:smooth;
}

推荐答案

有几种不同的解决方法,但我认为最好的方法是在每个节中放置一个隐藏的伪元素::before.这是仅CSS解决方案,没有JS或jQuery ...

There are a few different ways to solve it, but I think the best way is to put a hidden pseudo element ::before each section. This is a CSS only solution, no JS or jQuery...

section:before {
    height: 54px;
    content: "";
    display:block;
}

https://www.codeply.com/go/J7ryJWF5fr

这将放置占顶部Navbar所需的空间.您还需要删除#section1margin-top偏移量,因为此方法将对 all 部分始终有效,并允许scrollspy工作.

That will put the space needed to account for the fixed-top Navbar. You'll also want to remove the margin-top offset for #section1 since this method will work consistently for all sections and allow the scrollspy to work.

相关
如何操作我将数据偏移量添加到Bootstrap 4固定式顶部响应式导航栏中吗?
使用Bootstrap粘性导航栏的Href跳转

Related
How do I add a data-offset to a Bootstrap 4 fixed-top responsive navbar?
Href Jump with Bootstrap Sticky Navbar

这篇关于使用Bootstrap 4固定的导航栏在HTML中偏移滚动锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆