繁体   English   中英

使用CSS在div中垂直居中放置文本

[英]Position text vertically center in div with CSS

我想将所有文本垂直放置在div的中心。

目前,“立即在线与我们聊天”位于div的顶部。

如何使用我的代码实现这一目标?

小提琴: http : //jsfiddle.net/jL5bpmp1/

 * { margin:0 } .box { -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; background-color:#0f89cf; height:55px; width:100%; padding:5px 0 0 0; margin-bottom:30px } .box img, .box div { float:left; margin-left:10px } .box h1 { color:#fff; font-size:18px } .box h1 span { display:block; font-size:23px } 
 <div class="is-mobile"> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Chat to us online now</h1> </div> </div> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Call the Helpline <span>101 2333 9302</span></h1> </div> </div> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Make a General Enquiry <span>101 2333 9303</span></h1> </div> </div> </div> 

我建议使用display:inline-block而不是float:left ,然后可以轻松设置垂直对齐值。

.box img, .box div {
    display:inline-block;
    vertical-align:middle;
}

的jsfiddle

您可以使用以下常见的垂直居中方法:

.box div {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

 * { margin:0 } .box { -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; background-color:#0f89cf; height:55px; width:100%; padding:5px 0 0 0; margin-bottom:30px } .box img, .box div { float:left; margin-left:10px } .box h1 { color:#fff; font-size:18px } .box h1 span { display:block; font-size:23px } .box div { position: relative; top: 50%; transform: translateY(-50%); } 
 <div class="is-mobile"> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Chat to us online now</h1> </div> </div> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Call the Helpline <span>101 2333 9302</span></h1> </div> </div> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Make a General Enquiry <span>101 2333 9303</span></h1> </div> </div> </div> 

如果您的浏览器支持IE10 +,则可以使用flex-box。 您只需要添加两行:

.box {
    display: flex;
    align-items: center;
    padding: 0;
}

我还添加了padding: 0; 因为您现在不需要它,所以您正在使用flex-box。 欢迎来到未来。 了解flexbox的最佳地点在这里:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

暂无
暂无

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

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