使用flexbox在导航栏中垂直居中导航栏

时间:2015-06-22 06:06:59

标签: html css twitter-bootstrap flexbox

我对CSS非常糟糕,因此我无法将<li>(导航栏药片)垂直放在我的导航栏中。此导航栏来自twitter bootstrap

以下是导航栏的HTML:

  <div class="container">
    <nav class="navbar navbar-default navbar-fixed-top">
      <ul id="nav_pills" class="nav nav-pills" role="tablist">
        <li role="presentation">
          <a href="/">About</a>
        </li>
        <li role="presentation">
          <a href="/gallery">Gallery</a>
        </li>
        <li role="presentation">
          <a href="/news">News</a>
        </li>
        <li role="presentation">
          <a href="#history">History</a>
        </li>
        <li role="presentation">
          <a href="#contact">Contact</a>
        </li>
      </ul>
    </nav>
  </div>

我的导航栏目前看起来像这样:

enter image description here

我也试图使用flexbox,因为在浏览解决方案时,使用flexbox似乎是一种简单的方法来垂直居中我的导航栏按钮。

这是我目前所尝试的但它不起作用= /

.nav li {
    display: flex;
    flex-direction: row;
    align-items: baseline;
}

2 个答案:

答案 0 :(得分:5)

display: flex设置<ul class="nav">,而不为商品设置。{ 同时使用align-items: center进行垂直对齐:

&#13;
&#13;
.nav {
  height: 70px;
  
  display: flex;
  justify-content: center;
  align-items: center;
}
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
    <nav class="navbar navbar-default navbar-fixed-top">
      <ul id="nav_pills" class="nav nav-pills" role="tablist">
        <li role="presentation">
          <a href="/">About</a>
        </li>
        <li role="presentation">
          <a href="/gallery">Gallery</a>
        </li>
        <li role="presentation">
          <a href="/news">News</a>
        </li>
        <li role="presentation">
          <a href="#history">History</a>
        </li>
        <li role="presentation">
          <a href="#contact">Contact</a>
        </li>
      </ul>
    </nav>
  </div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

要垂直对齐它,请为列表元素设置一个等于导航栏高度的行高,然后删除顶部和底部填充。它根本不需要Flexbox:)

.nav > li > a {
    display: block;
    line-height: 50px; // Add
    padding: 0 15px; // Modify
    position: relative;
}

Bootply