我正在尝试将 Bootstrap 5 的
navbar
与 fixed-top
一起使用,其中所有导航项都是对页面上锚点的引用。当我点击当前位置下方的链接时,它会转到正确的位置,但是如果我在查看第 3 部分时点击,比如说“链接 1”,第 1 部分最终会把最上面的部分埋在下面导航栏。这是从这个 CopyCat.dev 示例稍作修改的一些代码
我在这里和其他地方看到答案说要在
margin-top
,body
或各个部分上放置<main>
。这些我都试过了。我也尝试过使用 padding-top
代替。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body data-bs-spy="scroll" data-bs-target=".navbar">
<nav class="navbar navbar-expand-lg bg-info fixed-top">
<div class="container-fluid">
<!-- Navbar title -->
<a class="navbar-brand" href="#">Bootstrap-Navbar</a>
<!-- Navbar mobile Hamburger -->
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar Items -->
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" href="#section-1">Link 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section-2">Link 2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section-3">Link 3</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section-4">Link 4</a>
</li>
</ul>
</div>
</div>
</nav>
<main class="pt-5">
<section
id="section-1"
class="vh-100 text-center fs-2 text-white bg-danger"
>
Section 1
</section>
<section
id="section-2"
class="vh-100 text-center fs-2 text-white bg-warning"
>
Section 2
</section>
<section
id="section-3"
class="vh-100 text-center p-5 fs-2 text-white bg-success"
>
Section 3
</section>
<section
id="section-4"
class="vh-100 text-center p-5 fs-2 text-white bg-info"
>
Section 4
</section>
</main>
<script type="module" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
</body>
</html>
我在 css 文件中添加了以下内容:
body {
padding-top: 0px;
}
section {
padding-top: 56px;
margin-top: -56px;
background-clip: content-box;
}
main {
padding-top: 56px;
}
这似乎已经解决了,至少在 Chrome 和 Firefox 上是这样。
添加CSS: 宽度:100px; 或者什么