Reputation: 1375
How do you vertically centered a text in the middle of a banner container with image tag?
My search result is using display:table/display:table-cell or display:inline-block but those solution didn't work when we have image tag. I think I have to have position absolute for text but then how to make sure it's always vertically and horizontally centered when re-sizing window?
Here is html:
<div class="banner">
<img class="" src="http://placehold.it/1440x410">
<div class="container">
<div class="banner-text">
<h1>Header Text</h1>
<h3>Sub Header Text</h3>
<a href="#"> CTA</a>
</div>
</div>
</div>
and Css as below:
.banner{
width: 100%;
position: relative;
}
.banner img{
width: 100%;
}
.container{
margin-left: auto;
margin-right: auto;
width: 100%;
}
.banner-text{
position: absolute;
top: 50%;
left: 50%;
}
http://codepen.io/neginbasiri/pen/grEmMx
I am wondering whats your solution for this?
Thanks
Upvotes: 0
Views: 41
Reputation: 7658
just add this transform to the class listed here:
.banner-text{
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%); /* or of course - translate(-50%, -50%); */
}
Check out this guide for more info: Centering in CSS
Upvotes: 2
Reputation: 19109
The most concise way to do what you need is the following:
.banner-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* add me */
}
Upvotes: 1