Bootstrap 4:如何使顶部固定的Navbar保持在容器中而不拉伸?

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:

通过添加针对.containernav.navbar规则,您的导航栏现在与父容器的宽度相同:

翻译自: https://www.freecodecamp.org/news/bootstrap-4-how-to-make-top-fixed-navbar-stay-in-container-and-not-stretch/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值