在引导程序导航栏中单独显示菜单项并使它们居中

时间:2016-03-10 07:32:57

标签: javascript jquery html css twitter-bootstrap

我想使用导航栏创建菜单按钮。我想这样做是因为它是小型设备的可折叠界面。

我写这个HTML标记:

<div class="container">
    <nav class="navbar" style="background-color: transparent;">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar" style="background-color: black;">
                    <span class="icon-bar" style="background-color: white;"></span>
                    <span class="icon-bar" style="background-color: white;"></span>
                    <span class="icon-bar" style="background-color: white;"></span>
                </button>
            </div>
            <div class="collapse navbar-collapse" id="myNavbar">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">Home</a></li>
                    <li><a href="#">Page 1</a></li>
                    <li><a href="#">Page 2</a></li>
                    <li><a href="#">Page 3</a></li>
                    <li><a href="#">Page 4</a></li>
                </ul>
            </div>
        </div>
    </nav>
</div>

和这种风格:

nav ul {
        width: 100%;
        text-align:center;
    }

        nav ul li {
            text-align: center;
            width: 17%;
            background-color: #dbd9d9;
            margin: 10px;
        }

但有一些问题:

  1. 此菜单项不在ul的中心位置。我如何将li中的所有ul集中在一起?

  2. 如果我以某个宽度调整窗口大小,此菜单会突破2行。我怎么能解决这个问题,我的菜单是md和lg尺寸的1行? enter image description here

  3. Demo

    由于

2 个答案:

答案 0 :(得分:2)

使用white-space: no-wrap将停止在ul

中包装的项目

Bootstrap将float: left放在我们需要覆盖的nav.li个元素上

将您的CSS更改为:

nav ul {
  width: 100%;
  text-align: center;
  white-space:nowrap /* <-- changed */
}

nav ul li {
  text-align: center;
  width: 17%;
  background-color: #dbd9d9;
  /*padding: 10px;*/
  margin: 10px;
  display: inline-block !important; /* <-- changed */
  float: none !important; /* <-- changed */
}

必须使用!important来覆盖bootstrap

Updated bootply

答案 1 :(得分:2)

通过HTML和removing width of li的更改,我可以按照您的意愿使用它。

 <ul class="row nav navbar-nav">
      <li class="active col-xs-3 col-sm-2 col-ms-2 col-lg-2"><a href="#">Home</a></li>
      <li class="col-xs-3 col-sm-2 col-ms-2 col-lg-2"><a href="#">Page 1</a></li>
      <li class="col-xs-3 col-sm-2 col-ms-2 col-lg-2"><a href="#">Page 2</a></li>
      <li class="col-xs-3 col-sm-2 col-ms-2 col-lg-2"><a href="#">Page 3</a></li>
      <li class="col-xs-3 col-sm-2 col-ms-2 col-lg-2"><a href="#">Page 4</a></li>
    </ul>

这是working Bootply

不要担心手动将宽度设置为li,请使用内置类的引导程序。上面的HTML也可以像下面那样重写。

<li class="col-xs-3 col-sm-2"><a href="#">Page 1</a></li>

您不必指定col-ms-2 col-lg-2,因为默认情况下,bootstrap framwework将向所有设备提供样式,直到给出该设备的特定规则。这里将对md设备和LG设备执行规则col-sm-2。但最好尽可能详细的做法。