将bootstrap下拉宽度设置为等于容器

时间:2014-07-13 14:24:48

标签: jquery css css3 twitter-bootstrap twitter-bootstrap-3

我有一个左边的260px宽,右边是260px宽。我的中心div是流畅的100%宽度。

点击右箭头/中心div,我想要一个与中心div容器宽度相同的dropdown。以下是我的代码和fiddle

<div class="navbar navbar-default" role="navigation">
  <div class="container-fluid">    
   <div class="row">
    <div class="leftBox pull-left" href="#">
      <img src="//placehold.it/258x58">
    </div>
    <div class="rightBox pull-right" href="#">
      Right Div
    </div>
     <div class="centerBox">
       <ul class="nav pull-right">
          <li class="dropdown" id="menuLogin">
            <a class="dropdown-toggle" href="#" data-toggle="dropdown" id="navLogin">
              <b class="glyphicon glyphicon-chevron-down"></b></a>
              <div class="dropdown-menu">
                <form class="form" id="formLogin"> 
                  <input name="username" id="username" placeholder="Username" type="text"> 
                  <input name="password" id="password" placeholder="Password" type="password"><br>
                  <button type="button" id="btnLogin" class="btn">Login</button>
                </form>
            </div>
          </li>
        </ul>
    </div>
  </div>
</div>
</div> 

http://www.bootply.com/82O0SgmP8p

2 个答案:

答案 0 :(得分:1)

为什么不使用grid system而不是左右浮动列?

使用网格你可以做这样的事情

<div class="container">
    <div class="row">
        <div class="col-sm-3 width-260">
            <!-- left box goes here -->
        </div>

        <div class="col-sm-6">
            <!-- centre box goes here -->
        </div>

        <div class="col-sm-3 width-260">
            <!-- right box goes here -->
        </div>
    </div>
</div>

然后将您的下拉列表放在中间列中。它会更容易以这种方式设置样式(即使其成为包含元素的width: 100%等。)

您需要做的就是添加一些自定义样式,以确保左右列固定在260px

更新:要使左右列260px固定宽度,请将其添加到样式表中:

.width-260 {
    width: 260px;
}

答案 1 :(得分:1)

这是一个基于jQuery的解决方案,它计算中心框的width(在load和窗口大小调整期间),然后将width分配给登录框和位置它酌情。

注意:请参阅内联注释以了解相关步骤。

$(document).ready(function(){
  var cntrboxWidth = $('#centerBox').width()-520; // Width of center box minus width of the two side boxez
  $('#navLogin + .dropdown-menu').width(cntrboxWidth); // Setting the width of Login box
  var extraWidth = $('#navLogin').outerWidth(); // Getting the width of the arrow icon box to adjust position
  $('#navLogin + .dropdown-menu').css('left',-(cntrboxWidth)+extraWidth); // Positioning the login box

  $(window).resize(function(){ // Adjusting position and size upon resizing window.
    cntrboxWidth = $('#centerBox').width()-520;
    $('#navLogin + .dropdown-menu').width(cntrboxWidth);
    extraWidth = $('#navLogin').outerWidth();
    $('#navLogin + .dropdown-menu').css('left',-(cntrboxWidth)+extraWidth); 
  });

});

Demo

编辑:要将登录框放在菜单正下方,请使用以下CSS。它不需要是动态的,因为根据CSS,你的菜单栏有一个固定的高度(60px)。

.dropdown-menu{
    top: 60px; // Equal to the height of the menu
}
相关问题