I’m sorry for my question is may be duplicated to this:
Bootstrap fixed navbar inside div or this:
Twitter Bootstrap: How to make top fixed navbar stay in container and not stretch?
or many similiar, but three years has passed, and Bootstrap has almost updated it’s version from 2-nd to 4-th but problems remains still the same.
So I’m looking for some elegant and simple way to make fixed navbar stay inside parents div.container.
Here’s the code, that I’ve copied and changed a little bit, from official documentation:
<div class="container">
<nav class="navbar navbar-fixed-top navbar-light bg-faded">
<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>
6
Answers
Thank you for all your answers, but I've found at last an answer here: Fixed position but relative to container
This custom CSS is really helpful:
Edit – I mistakenly gave a Booststrap 3 answer instead of Boostrap 4.
You want to put the “container” div inside your nav.
This was a little bit tricky.
In addition to placing the
<div class="container"></div>
insidenav.navbar
, I had to use the following CSS so that the toggler and the logo didn’t overlap on mobile:My navbar code looks like this (generic):
My navbar code looks like this (for wordpress):
JSFIDDLE
I have found the simplest solution is to remove the .navbar-fixed-top class from the
<nav>
element and apply it to the<div class="container">
that wraps your<nav>
. This solution does not require any custom CSS and works across devices.If you want the nav in the body, put the nav in container div and add
sticky-top
class to the container. Do not applysticky-top
to the nav element.