使用flex align-items center将div中的文本垂直居中

时间:2017-01-13 06:14:29

标签: html css css3 flexbox height

我无法弄清楚我的CSS有什么问题。我认为这会将文本垂直居中在这个div中:



.content-bar {
  height: 60px;
  background: #f7f7f7;
  overflow: hidden;
  border-bottom: 1px solid #ececec;
}
.content-bar-content {
  display: flex;
  align-items: center;
}

<div class="content-bar">
  <div class="content-bar-content">
    Testing 123
  </div>
</div>
&#13;
&#13;
&#13;

但是,文本排在div的顶部。我错过了什么?

请参阅codepen:https://codepen.io/anon/pen/xgOwwp

5 个答案:

答案 0 :(得分:0)

查看演示,我已交换高度

.content-bar {
  
  background: #f7f7f7;
  overflow: hidden;
  border-bottom: 1px solid #ececec;
}
.content-bar-content {
    display:flex;
    align-items:center;
    height: 60px;
}
<div class="content-bar">
  <div class="content-bar-content">
    Testing 123
  </div>
</div>

答案 1 :(得分:0)

必须在父容器中声明所有CSS。这是一个水平和垂直居中的例子:

&#13;
&#13;
.content-bar {
  height: 80px;
  background: #f7f7f7;
  overflow: hidden;
  border-bottom: 1px solid #ececec;
  display:flex;
  align-items:center;
  justify-content: center;
}
&#13;
<div class="content-bar">
  <div class="content-bar-content">
    Testing 123
  </div>
</div>
&#13;
&#13;
&#13;

希望这有帮助!

答案 2 :(得分:0)

您可以将content-bar指定为flexbox,如下所示:

.content-bar {
  height: 60px;
  background: #f7f7f7;
  overflow: hidden;
  border-bottom: 1px solid #ececec;
  display: flex;
  align-items: center;
}
.content-bar-content {}
<div class="content-bar">
  <div class="content-bar-content">
    Testing 123
  </div>
</div>

或者您可以继承 content-bar的高度 - 只需在height: inherit上添加content-bar-content - 请参阅下面的演示:

.content-bar {
  height: 60px;
  background: #f7f7f7;
  overflow: hidden;
  border-bottom: 1px solid #ececec;
}
.content-bar-content {
  display: flex;
  align-items: center;
  height: inherit;
}
<div class="content-bar">
  <div class="content-bar-content">
    Testing 123
  </div>
</div>

答案 3 :(得分:0)

为两个类添加高度,并将addvertical-align:middle添加到内容

&#13;
&#13;
.content-bar {
  height: 60px;
  background: #f7f7f7;
  overflow: hidden;
  border-bottom: 1px solid #ececec;
  height:100%
}
.content-bar-content {
    height:100%;
    display:flex;
    align-items:center;
   vertical-align: middle;
}
&#13;
<div class="content-bar">
  <div class="content-bar-content">
    Testing 123
  </div>
</div>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

尝试使用这个简单的代码来对齐div中心的文本,删除固定高度并给出填充

.content-bar {
  padding:30px;
  height:auto;
  background: #f7f7f7;
  overflow: hidden;
  border-bottom: 1px solid #ececec;
}
.content-bar-content {
    display:flex;
    text-align:center;
}
<div class="content-bar">
  <div class="content-bar-content">
    Testing 123<br/> Testing 123<br/> Testing 123<br/> Testing 123<br/>
  </div>
</div>

相关问题