There are many ways to make a fixed navbar stay inside a parent's div
container. We'll go over the most straightforward one here.
有很多方法可以使固定的導航欄停留在父級的div
容器中。 我們將在這里介紹最簡單的方法。
Imagine you have the following code, modified slightly from the Bootstrap docs:
想象一下,您有以下代碼,是從Bootstrap文檔中稍作修改的:
<div class="container"><nav class="navbar navbar-fixed-top navbar-inverse bg-inverse"><button class="navbar-toggler hidden-lg-up" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button><div class="collapse navbar-toggleable-md" id="navbarResponsive"><a class="navbar-brand" href="#"><img src="" width="30" height="30" class="d-inline-block align-top" alt="">Navbar</a><ul class="nav navbar-nav float-md-right"><li class="nav-item active"><a class="nav-link" href="#">Home<span class="sr-only">(current)</span></a></li><li class="nav-item"><a class="nav-link" href="#">Link</a></li><li class="nav-item"><a class="nav-link" href="#">Link</a></li></ul></div></nav><div class="next"></div>hello
</div>
div.next {background-color: lightblue;width: 100%;height: 60rem;
}
And your page looks like this:
您的頁面如下所示:
解決方案 (Solutions)
While the docs read "Navbars and their contents are fluid by default. Use optional containers to limit their horizontal width," the easiest solution is to use CSS to set the width of the navbar directly:
當文檔閱讀“導航欄及其內容默認情況下是可變的。使用可選容器限制其水平寬度”時,最簡單的解決方案是使用CSS直接設置導航欄的寬度:
div.next {background-color: lightblue;width: 100%;height: 60rem;
}.container {padding: 0px;
}nav.navbar {width: inherit;top: 0%;left: 50%;transform: translateX(-50%);
}
By adding rules targeting .container
and nav.navbar
, your navbar is now the same width as the parent's container:
通過添加針對.container
和nav.navbar
規則,您的導航欄現在與父容器的寬度相同:
翻譯自: https://www.freecodecamp.org/news/bootstrap-4-how-to-make-top-fixed-navbar-stay-in-container-and-not-stretch/