Bootstrap 3 dropdown menu center align not working

坚强是说给别人听的谎言 提交于 2019-12-29 03:38:20

问题


I am not able to align the dropdown to the center of the parent on which the dropdown is opened with hover. I have tried to text-align: center for the entire .nav .navbar li elements, and it doesn't work. I have tried to set margin and left: 50% for the entire ul.dropdown-menu that is the dropdown and it doesn't work. Here is the html code:

<ul class="nav navbar-nav navbar-right" id="headerDropdowns">
  <li><div class="btn-toolbar">
    <div class="btn-group">
      <button class="btnCustom" data-toggle="dropdown" data-hover="dropdown" data-delay="1000">Our Difference</button>
      <ul class="dropdown-menu">
        <li><a tabindex="-1" href="#">Made in the USA</a></li>
        <li class="divider"></li>
        <li><a tabindex="-1" href="#">Human Grade</a></li>
        <li class="divider"></li>
        <li><a tabindex="-1" href="#">Ingredients Fresh</a></li>
        <li class="divider"></li>
        <li><a tabindex="-1" href="#">USDA Meats</a></li>
        <li class="divider"></li>
        <li><a tabindex="-1" href="#">Our Story</a></li>
        <li class="divider"></li>
        <li><a tabindex="-1" href="#">Campare</a></li>
      </ul>
    </div>
  </li>
</ul>

In which class dropdown-menu, or nav navbar-nav, should I do the aligment, and what should I set?


回答1:


You can use transform to avoid having to use fixed widths:

.dropdown-menu {
  left: 50%;
  right: auto;
  text-align: center;
  transform: translate(-50%, 0);
}

Answer influenced by http://css-tricks.com/centering-percentage-widthheight-elements/




回答2:


You can do this as long as you're willing to give the dropdown ul a fixed width. See code below:

.dropdown{text-align:center;}
.button, .dropdown-menu{margin:10px auto}
.dropdown-menu{width:200px; left:50%; margin-left:-100px;}

First 2 declarations are for visualization purposes, but the important part is the 3rd line. You'll need to define a width (in this case 200px) and then a margin-left equal to half the width. This will work with any width, no matter if the button is at the right, left or between elements (but of course you'll probably need some space for the button element)

You can see a fiddle here




回答3:


The only, ugly way is to set the position depending on your needs like:

.dropdown-menu{
    right: -25px !important;
}

Fiddle

But thas not the way it should be used. Keep in mind that you have to adjust the setting for all media devices.




回答4:


This is what did the trick for me:

.dropdown-menu{
    left: -25% !important;
}

You might need to adjust the percentage value depending on your dropdown-menu's padding etc.



来源:https://stackoverflow.com/questions/25610774/bootstrap-3-dropdown-menu-center-align-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!