Reputation: 711
I’m currently using Bootstrap 4’s dropdown. How do I change the following code so that the dropdown menu that appears after you click the button is the same width as the button itself?
Note that the size of the button can change based on the text that is inside and I’d like the dropdown menu that appears to be the same regardless of the text.
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div class="dropdown-menu w-100" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else
here</a>
</div>
</div>
https://jsfiddle.net/5mqg7dgv/
Thanks in advance for any help.
Upvotes: 2
Views: 6205
Reputation: 8126
As <div>
s are block level elements, they take up all the available space horizontally. So, .w-100
on the .dropdown-menu
itself extends it's boundaries to the width of the parent, which is not just the visible part of the button.
One way to solve this is to render the .dropdown
as an inline block by applying .d-inline-block
on it, like so:
<div class="dropdown d-inline-block">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div class="dropdown-menu w-100" aria
labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else
here</a>
</div>
</div>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
Upvotes: 3