When I place a bootstrap dropdown inside a div that centers the dropdown using CSS "text-align: center", the dropdown menu appears in the original un-centered position of the dropdown. The dropdown doesn't seem to know that its triggering button has been moved.
The issue is represented in this jsfiddle:
https://jsfiddle.net/dkent600/wyos4ukt
The fiddle contains the following code:
<div style="background-color:grey; text-align:center">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
</ul>
</div>
</div>
Thanks for any clues for how to fix this.
Use data-offset or data-reference to change the location of the dropdown.
Example Explained HTML) Use any element to open the dropdown content, e.g. a <span>, or a <button> element. Use a container element (like <div>) to create the dropdown content and add whatever you want inside of it. Wrap a <div> element around the elements to position the dropdown content correctly with CSS.
Solution : The dropdown should be toggled via data attributes or using javascript. In the above program, we have forgotten to add a data attribute so the dropdown is not working. So add data-bs-toggle="dropdown" to toggle the dropdown.
Use the w3-right class to float the dropdown to the right, and use CSS to position the dropdown content (right:0 will make the dropdown menu go from right to left).
If you add the class btn-group
to the .dropdown
element, then the dropdown-menu will be positioned properly.
Updated Exmple
<div class="btn-group dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
The reason this works is because the class adds the following CSS. In doing so, the dropdown-menu is positioned absolutely relative to the parent element.
.btn-group > .btn,
.btn-group-vertical > .btn {
position: relative;
float: left;
}
Alternatively, you could also add the following:
Updated Example
.dropdown {
position: relative;
display: inline-block;
vertical-align: middle;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With