Search code examples
htmlcssbootstrap-4dropdown

how to solve positioning problem of dropdown menu


this is my html and css code right now

<div class="header">
<div class="container-fluid">
  <div class="row">
    <div class="col-1"></div>
    <div class="col-10"></div>
    <div class="col-1 dropdown">
      <button class="btn" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true"
        aria-expanded="false">
        Menu
        <i class="fa fa-bars"></i>
      </button>
      <div class="dropdown-menu">
        <a class="dropdown-item" href="#">About </a>
        <a class="dropdown-item" href="#">Education</a>
        <a class="dropdown-item" href="#">Hobbies</a>
        <a class="dropdown-item" href="#">Contact</a>
      </div>
    </div>
  </div>
</div>

.header{
position: relative;
top: 20px;
}

.dropdown-menu {
min-width: 120px !important;
height: 145px !important;
position: relative;
right: 0;
}

body {
background-color: lightblue;
} 

i want to make it so that the dropdown menu is shifted to the right instead of the left what i want to achieve but what i got with my code was this what i got


Solution

  • You don't need any custom css for this if you are using bootstrap.

    By default, a dropdown menu is automatically positioned 100% from the top and along the left side of its parent. Add .dropdown-menu-right to a .dropdown-menu to right align the dropdown menu.

    Refer: https://getbootstrap.com/docs/4.0/components/dropdowns/#menu-alignment

    Demo: https://jsfiddle.net/7aso841L/

    <div class="header">
      <div class="container-fluid">
        <div class="row">
          <div class="col-1"></div>
          <div class="col-10"></div>
          <div class="col-1 dropdown">
            <button class="btn" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Menu
              <i class="fa fa-bars"></i>
            </button>
            <div class="dropdown-menu dropdown-menu-right">
              <a class="dropdown-item" href="#">About </a>
              <a class="dropdown-item" href="#">Education</a>
              <a class="dropdown-item" href="#">Hobbies</a>
              <a class="dropdown-item" href="#">Contact</a>
            </div>
          </div>
        </div>
      </div>