Flexbox导航栏,拉伸链接等于高度

时间:2016-01-13 14:33:41

标签: html css css3 flexbox

我有一个导航栏,当视口有点窄时,有一些链接可以包含2+行。我想使所有导航项目具有相同的高度,并使其文本保持垂直居中。到目前为止,我已经能够将所有内容垂直居中,但我无法将<a>'s的高度与所有匹配相匹配。请参阅下面的codepen示例...

http://codepen.io/anon/pen/GovmZa

&#13;
&#13;
.container {
  width:950px;
  margin:0 auto;
}

ul {
  display:flex; 
  align-items: stretch; 
  justify-content: flex-start;
}

li {
  list-style-type:none; 
  display:flex;
  flex-grow:1;
  align-items:center;
  flex-direction: column;
  text-align:center;
  border:1px solid #fff;
  text-align:center;
}

a {

  color:#fff;
  padding:10px;
  margin-right:1px;
  flex: 1;
  display: flex;
  align-content: center;
  align-items: center;
  text-align:center;
  background-color:#000;
}
&#13;
<div class="container">
  <p>How do I make the links stretch to be equal heights and keep text vertically aligned in the center?</p>
  <ul>
    <li>
      <a href="#">Can</a>
    </li>
    <li>
      <a href="#">somebody please help me figure</a>
    </li>
    <li>
      <a href="#">this</a>
    </li>
    <li>
      <a href="#">out</a>
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:6)

每个列表项(li)已经是灵活容器,但请尝试将方向更改为column

然后给锚点flex: 1,因此它们占据了所有可用空间。

li { flex-direction: column; }
a  { flex: 1; }

要保持文本水平和垂直居中,请将text-align: center添加到li并使锚点展开容器,同时添加align-*属性。

li { 
  flex-direction: column;
  text-align: center;
}

a {
  flex: 1;
  display: flex;
  align-content: center; /* will vertically center multi-line text */
  align-items: center;   /* will vertically center single-line text */
}

Revised Codepen

答案 1 :(得分:1)

李的高度都是一样的,它是问题中的锚标签。

为这些设置应用一些柔性造型,它可以解决您的问题

&#13;
&#13;
.container {
  width:300px;
  margin:0 auto;
}

ul {
  display:flex;  
  justify-content: flex-start;
}

li {
  list-style-type:none; 
  display:flex;
  align-items: stretch; 
  flex-grow:1;
}

a {
  display:flex;
  align-items: center; 
  background-color:#000;
  color:#fff;
  padding:10px;
  align-content: center;
  margin-right:1px;
}
&#13;
<div class="container">
  <p>How do I make the links stretch to be equal heights and keep text vertically aligned in the center?</p>
<ul>
  <li>
    <a href="#">Can</a>
  </li>
  <li>
    <a href="#">somebody please help me figure</a>
  </li>
  <li>
    <a href="#">this</a>
  </li>
  <li>
    <a href="#">out</a>
  </li>
</ul>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我&#34;解决了#34;使用此代码..但最好等待更好的回复..

.container {
  width:600px;
  height:100px;
  margin:0 auto;
}

ul {
  display:flex; 
  align-items: stretch; 
  justify-content: flex-start;
  width:100%;
}

li {
  list-style-type:none; 
  display:flex;
  flex-grow:1;
  align-items:center;
}

a {
  background-color:#000;
  color:#fff;
  padding:10px;
  align-content: center;
  margin-right:1px;
  height:25px;
  width:100%;
}