使用flexbox无法使元素垂直对齐

时间:2016-08-01 15:24:39

标签: css flexbox

我花了几个小时试图让我的flex元素中的文本垂直对齐而没有运气。感觉就像我在这里缺少一些非常重要的东西!

enter image description here

HTML

<div class="flex-container">
    <div class="flex-item">
        test
    </div>                                     
    <div class="flex-item">
        test                                   
    </div>                                   
</div>

CSS

.flex-container {
    height:100%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: center;
    align-content: stretch;
    align-items: stretch; 
}

.flex-item {
    flex: 1 auto;
}

2 个答案:

答案 0 :(得分:1)

display:flex未被继承,因此您需要将其应用于flex-items ...使用align-items将文本垂直居中。

html,
body {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  height: 100%;
  margin: 0;
  padding: 0;
}
.flex-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: center;
  align-content: stretch;
  align-items: stretch;
}
.flex-item {
  flex: 1 auto;
  display: flex;
  align-items: center; /* center vertically */
  justify-content:center; /* center horzontally */
  border: 1px solid grey
}
<div class="flex-container">
  <div class="flex-item">
    test
  </div>
  <div class="flex-item">
    test
  </div>
</div>

答案 1 :(得分:0)

<强>问题:

问题是您的.flex-containter没有到达您的测试文本,因为它不是它的孩子,它是.flex-item的后代。

  

Flex容器的内容由零个或多个弹性项组成:   Flex容器的每个子节点都变为弹性项目。

每个弹性项目都受弹性容器的影响,但弹性项目的后代不受此影响。

<强> SOLUTION:

您还需要将display: flex;添加到您的Flex项目中。

<强> JSFIDDLE

CODE SNIPPET

.flex-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: center;
  align-content: stretch;
  align-items: stretch;
}
.flex-item {
  flex: 1 auto;
  display: flex;
  align-items: center;
  height: 200px;
  background-color: royalblue;
  color: white;
}
.flex-item:nth-of-type(2) {
  background-color: tomato;
}
<div class="flex-container">
  <div class="flex-item">
    test
  </div>
  <div class="flex-item">
    test
  </div>
</div>