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
<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/
Is it because I am not specifying the width of the image in parent div?
Any help is highly appreciated.
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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.