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

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

问题描述

所以,我有这个由几个部分组成的页面.用户可以通过滚动自己或单击导航栏(带有锚点的 href)来访问这些部分.由于 Bootstrap 4 导航栏固定在顶部,内容被放置在其下方.有没有一种方法可以让锚点偏移 -54px,这样每当我点击一个锚点链接时,它就会显示导航栏下方(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).

制作此代码笔以显示我面临的问题:
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

这将放置占固定顶部导航栏所需的空间.您还需要删除 #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 固定顶部响应式导航栏添加了数据偏移量?
Href Jump with Bootstrap Sticky Navbar

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

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