HTML/CSS problem with the dropdown menu not being centered under the button

Viewed 95

enter image description here

I'm trying to make the menu centered under the button. Currently, it's left-aligned.

Here is the code:

.role_select {
    margin: auto;
}

#role_select > div {
    margin-top: 5%;
}

ul[aria-labelledby="dropdownMenuButton1"] > li {
    text-align: center;
}

ul[aria-labelledby="dropdownMenuButton1"] {
    border: 2px solid red;
}
<div class="role_select">
            <button
                class="btn btn-secondary dropdown-toggle"
                type="button"
                id="dropdownMenuButton1"
                data-bs-toggle="dropdown"
                aria-expanded="false"
            >
                Select Role
            </button>

            <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
                <li @click="id_drop(0)">MT-Almighty</li>
                <li @click="id_drop(1)">ST-Almighty</li>
            </ul>
</div>

E:

I've seen dropdown-menu-right and stuff, but there doesn't seem to be one for middle or center.

2 Answers
  • You can either use a margin left/right property to center align the dropdown

or

  • You can use the block method like this :
<div class="role_select">
            <button class="btn btn-secondary dropdown-toggle">
                Select Role
            </button>

            <ul class="dropdown-menu">
                <li>MT-Almighty</li>
                <li>ST-Almighty</li>
            </ul>
</div>
  • define a width for class="role_select" so that class="dropdown-menu" can easily come within it and define btn-secondary dropdown-menu both classes display property as display:block. Then you can center align bothusing margin-left:auto;margin-right:auto;text-align:center like this :
.role{
  width:10%;/*20%,100px,....your wish so thatdropdown can eassily come */
}
.dropdown-menu{
  display:block;
  margin-left:auto;
  margin-right:auto;
  text-align:center
}
.btn-secondary{
  display:block;
  margin-left:auto;
  margin-right:auto;
  text-align:center
}

Turns out I was looking for the wrong thing.

position dropdown button and dropdown menu in center?

I added a new class to the ul tag which solved it.

Margin-top had to be eyeballed with pixels for some reason since percentage changed made the menu was lower than it should be when the screen became narrow.

    .dropdown-menu-center {
        left: 50% !important;
        right: auto !important;
        margin-top: 68px !important;
        text-align: center !important;
        transform: translateX(-50%) !important;
        position: fixed !important;
    }
'''
Related