为什么我不能将内联flex项目居中?

时间:2018-02-19 10:16:06

标签: html css css3 flexbox

我正在使用flexbox创建导航栏,并在尝试使用锚标签创建按钮时遇到此特定问题(即在框中心的链接)。

我将li设置为显示flex,以便我可以将a置于中心位置,但只要我将a设置为某个高度,a就会对齐a左上方。有没有办法让* { box-sizing: border-box; } html, body { margin: 0; padding: 0; font: sans-serif; } #top-nav { border-bottom: 4px solid blue; } #center-section { display: flex; width: 1000px; margin: auto; } #center-section>* { flex: 1 1 0; } header section { background: blue; height: 90px; width: 500px; } .navbar { display: flex; } .navbar ul { list-style-type: none; padding: 0; display: flex; flex-direction: row; width: 100%; height: 100%; align-self: center; border: 1px solid red; } .navbar ul li { display: flex; flex: 1 1 100%; } .navbar ul li a { background-color: yellow; align-self: center; width: 100%; height: 100%; } .navbar ul li a:hover { background-color: green; }居中?

<header>
  <div id="top-nav">
    <div id="center-section">
      <section id="logo">
        <a href="">Home</a>
      </section>
      <div class="navbar">
        <ul>
          <li><a href="">About</a></li>
          <li><a href="">Store</a></li>
          <li><a href="">Contact</a></li>
        </ul>
      </div>
    </div>
  </div>
</header>
Private WithEvents barcodeReader As Barcode.Barcode = New Barcode.Barcode

1 个答案:

答案 0 :(得分:4)

当您将高度:100%设置为a时,您可以将其拉伸到所有li,因此您无法再控制它,因为在这种情况下所有对齐都是等效的。您需要的是将内容对齐 a。为此,您可以将其设为灵活容器,并使用align-items和/或justify-content

&#13;
&#13;
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  font: sans-serif;
}

#top-nav {
  border-bottom: 4px solid blue;
}

#center-section {
  display: flex;
  width: 1000px;
  margin: auto;
}

#center-section>* {
  flex: 1 1 0;
}

header section {
  background: blue;
  height: 90px;
  width: 500px;
}

.navbar {
  display: flex;
}

.navbar ul {
  list-style-type: none;
  padding: 0;
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
  align-self: center;
  border: 1px solid red;
}

.navbar ul li {
  display: flex;
  flex: 1 1 100%;
}

.navbar ul li a {
  background-color: yellow;
  display:inline-flex;
  align-items: center;
  justify-content:center;
  width: 100%;
  height: 100%;
}

.navbar ul li a:hover {
  background-color: green;
}
&#13;
<header>
  <div id="top-nav">
    <div id="center-section">
      <section id="logo">
        <a href="">Home</a>
      </section>
      <div class="navbar">
        <ul>
          <li><a href="">About</a></li>
          <li><a href="">Store</a></li>
          <li><a href="">Contact</a></li>
        </ul>
      </div>
    </div>
  </div>
</header>
&#13;
&#13;
&#13;