简体   繁体   English

在图像顶部垂直对齐中间和居中的文本

[英]Vertical align middle and centered text on top of image

I am trying to place the text over an image using vertical aligned middle and text align center. 我正在尝试使用垂直对齐的中间和文本对齐中心将文本放置在图像上。 But none of them seems working. 但是它们似乎都不起作用。

My html is 我的HTML是

<div class="hero-image">
  <img src="https://s23.postimg.org/ahcg75tsb/hero.png" alt="">
  <a href=""><h2>Some Sample text</h2></a>
</div>

Demo -- https://jsfiddle.net/squidraj/zkno1sc2/ 演示-https: //jsfiddle.net/squidraj/zkno1sc2/

Is it because I am not specifying the width of the image in parent div? 是否因为我未在父div中指定图像的宽度?

Any help is highly appreciated. 非常感谢您的帮助。

You can use display: flex on the .hero-image in combination with align-items: center; 您可以将display: flex.hero-image上与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> 

Make the "top" padding, See the code: 进行“顶部”填充,请参见代码:

 .hero-image { display: block; position: relative; } .hero-image a { background: #ff2bff none repeat scroll 0 0; color: #fff; left: 0; position: absolute; right: 0; text-align: center; top: 45%; width: 200px; bottom: 0; vertical-align: middle; text-align: center; margin: 0px auto; height: 50px } 
 <div class="hero-image"> <img src="https://s23.postimg.org/ahcg75tsb/hero.png" alt=""> <a href=""><h2>Some Sample text</h2></a> </div> 

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

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