繁体   English   中英

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

[英]Using flex align-items center to vertically center text inside div

我无法弄清楚我的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> 

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

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

检查演示,我已交换高度

 .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> 

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

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

希望这可以帮助!

您可以将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 - 只需添加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> 

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

 .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; } 
 <div class="content-bar"> <div class="content-bar-content"> Testing 123 </div> </div> 

尝试使用这个简单的代码来对齐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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM