CSS:如何在图像上垂直和水平居中放置文本 [英] CSS: How to center text vertically and horizontally over an image
本文介绍了CSS:如何在图像上垂直和水平居中放置文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要做的就是将文本垂直和水平居中放置在img上。
All I want to do is center my text vertically and horizontally on an img..
尝试了很多东西,但到目前为止没有任何效果:/
Tried a lot of things but nothing works so far :/
<div class="img_container">
<img class="cover-image" src="img.jpg" alt="omg" />
<h2> bla bla bla </h2>
</div>
.img_container {
width: 100%;
}
.img_container h2 {
margin: 0;
}
推荐答案
只使用绝对位置并翻译。会完美居中(水平和垂直)
Just use position absolute and translate. Will be perfect centered (horizontally and vertically)
.img_container {
position: relative;
}
.img_container img {
width: 100%;
height: auto;
}
.img_container h2 {
color: white;
text-shadow: 1px 1px 1px black;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%); /* iOS */
transform: translate(-50%, -50%);
}
<div class="img_container">
<img class="cover-image" src="http://lorempixel.com/400/200/sports/" alt="omg" />
<h2> bla bla bla </h2>
</div>
这篇关于CSS:如何在图像上垂直和水平居中放置文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文