First you have to leave the container dropdown
with the width of the largest content. for this I created a class custom and put the width
as max-content
.
Then we’ll adjust the left
and transform the original dropdown
. It by default already has these properties, but to centralize vc need to adjust them, the way I did, regardless of the size of the content it will always center on the button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" media="screen"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<style>
.drop-custom.show {
width: max-content;
}
.drop-custom.show .dropdown-menu {
left: 50% !important;
transform: translate3d(-50%, 38px, 0px) !important;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<div class="dropdown drop-custom">
<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" 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 12312312321</a>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
</body>
</html>
Add the code to your menu as well to make it easier to help you...
– Lodi
@Lodi I added the code.
– Thiago Krempser
If the button is in the left corner, when centering the menu, it will exit the screen because of the width. You want to move the button to the right?
– Sam
@Sam I’ll put the button inside a container after centralized.
– Thiago Krempser