I am creating a navbar using Bootstrap4 and adding a nav-item button to dropdown a menu. But the problem is that other nav-items are pushed around (changing position) when menu drops down. The below code demonstrates a horizontal pushing around of the last item. But in my site which contains a few more nav-items the drop down also causes vertical movement of other nav-items.
Additionally if I make add the class dropdown-toggle
to the button I get a very ugly expand_more
text next to the butto.
What is wrong with below code?
<nav class="navbar navbar-inverse fixed-top">
<ul class="nav navbar-nav bd-navbar-nav flex-row">
<li id="ncx1" class="nav-item">
item1
</li>
<li id="ncx1" class="nav-item">
item2
</li>
<li id="nvps0add" class="nav-item ml-3">
<div class="dropdown"
id="add_dropdown"
>
<button type="button" class="btn border-0"
role="button"
data-toggle="dropdown"
style="padding:0; background: transparent;"
aria-haspopup="true" aria-expanded="false"
>
dropdown
</button>
<div class="dropdown-menu dropdown-menu-right"
aria-labelledby="add_dropdown"
>
<a class="dropdown-item" href="#">
dropitem1
</a>
<a class="dropdown-item" href="#">
dropitem2
</a>
</div>
</div>
</li>
<li id="nvps0delete" class="nav-item ml-3">
item3
</li>
</ul>
</nav>
Demo: https://jsfiddle.net/b23catgp/
Explanation:
You needed to change the css property position from static to absolute. I've included a good link about the difference but to summarize...a static positioned element is based on its current position in the flow while an absolute positioned element is positioned based on its closest positioned ancestor position. The dropdown when active since it was static was pushing over the rest of the nav-items in your navigation. You didn't want this behavior so to have the other elements fill in where the dropdown would have filled in space you have to give it absolute position.
What you have to add to your existing code:
/* New */
.dropdown-menu {
position: absolute !important;
}
Additionally, in the demo above I added back in the 'dropdown-toggle' class to the button and it's working fine.