Bootstrap: Position of dropdown menu relative to navbar item
Solution 1:
This is the effect that we're trying to achieve:
The classes that need to be applied changed with the release of Bootstrap 3.1.0 and again with the release of Bootstrap 4. If one of the below solutions doesn't seem to be working double check the version number of Bootstrap that you're importing and try a different one.
Bootstrap 3
Before v3.1.0
You can use the pull-right
class to line the right hand side of the menu up with the caret:
<li class="dropdown">
<a class="dropdown-toggle" href="#">Link</a>
<ul class="dropdown-menu pull-right">
<li>...</li>
</ul>
</li>
Fiddle: http://jsfiddle.net/joeczucha/ewzafdju/
After v3.1.0
As of v3.1.0, we've deprecated .pull-right on dropdown menus. To right-align a menu, use .dropdown-menu-right. Right-aligned nav components in the navbar use a mixin version of this class to automatically align the menu. To override it, use .dropdown-menu-left.
You can use the dropdown-right
class to line the right hand side of the menu up with the caret:
<li class="dropdown">
<a class="dropdown-toggle" href="#">Link</a>
<ul class="dropdown-menu dropdown-menu-right">
<li>...</li>
</ul>
</li>
Fiddle: http://jsfiddle.net/joeczucha/1nrLafxc/
Bootstrap 4
The class for Bootstrap 4 are the same as Bootstrap > 3.1.0, just watch out as the rest of the surrounding markup has changed a little:
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#">
Link
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#">...</a>
</div>
</li>
Fiddle: https://jsfiddle.net/joeczucha/f8h2tLoc/
Solution 2:
Not sure about how other people solve this problem or whether Bootstrap has any configuration for this.
I found this thread that provides a solution:
https://github.com/twbs/bootstrap/issues/1411
One of the post suggests the use of
<ul class="dropdown-menu" style="right: 0; left: auto;">
I tested and it works.
Hope to know whether Bootstrap provides config for doing this, not via the above css.
Cheers.
Solution 3:
Based on Bootstrap doc:
As of v3.1.0, .pull-right is deprecated on dropdown menus. use .dropdown-menu-right
eg:
<ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dLabel">