在图像顶部垂直对齐中间和居中的文本
问题描述:
我正在尝试使用垂直对齐的中间和文本对齐中心将文本放置在图像上。
I am trying to place the text over an image using vertical aligned middle and text align center. But none of them seems working.
我的html是
<div class="hero-image">
<img src="https://s23.postimg.org/ahcg75tsb/hero.png" alt="">
<a href=""><h2>Some Sample text</h2></a>
</div>
演示- https://jsfiddle.net/squidraj/zkno1sc2/
是因为我没有指定图像的宽度在父div中?
Is it because I am not specifying the width of the image in parent div?
任何帮助都将受到高度赞赏。
Any help is highly appreciated.
答
您可以在 .hero-image
上结合使用 display:flex
和 align-items :中心;
:
You can use display: flex
on the .hero-image
in combination with align-items: center;
:
.hero-image {
display: flex;
position: relative;
align-items: center;
}
.hero-image img{
width: 100%;
}
.hero-image h2 {
background: #ff2bff none repeat scroll 0 0;
color: #fff;
text-align: center;
width: 200px;
margin: 0px auto;
position: absolute;
left: 0;
right: 0;
}
<div class="hero-image">
<img src="https://s23.postimg.org/ahcg75tsb/hero.png" alt="">
<a href=""><h2>Some Sample text</h2></a>
</div>
div>