Reputation: 2299
I'm trying to vertically center text inside a div that is positioned absolutely.
I have tried table-cell
approach with no luck. This is a responsive layout, so I'm trying to avoid setting fixed heights and prefer not to use Javascript either.
Thanks
HTML & CSS:
<div class="page-banner" style="background: url(http://www.bimga.com.php53-3.ord1-1.websitetestlink.com//wp-content/uploads/BIMGA_Website_InteriorPage_Banners_About.jpg) no-repeat scroll 0 0 / cover transparent">
<img style="visibility:hidden" src="http://www.bimga.com.php53-3.ord1-1.websitetestlink.com//wp-content/uploads/BIMGA_Website_InteriorPage_Banners_About.jpg">
<div class="left">
<div class="page-banner-text">this text needs to be verticall centered</div>
</div>
</div>
<style type="text/css">
.page-banner {
margin-bottom: 35px;
list-style: none;
width: 100%;
padding-left: 0;
position: relative;
}
.page-banner img {
width: 100%;
height: auto;
}
.page-banner .left {
background-color: rgba(10, 65, 142, .75);
position: absolute;
z-index: 1;
left: 0;
top: 0;
height: 100%;
text-align: center;
width: 50%;
}
</style>
Upvotes: 6
Views: 2005
Reputation: 1325
I would not prefer using position absolute and top: 50% for better multi browser support (espesially on older IE versions) so I would prefer adding line-height: x em; in your .page banner class. Em because you have defined the height by % so it needs to always be on the center no matter the actual pixel height.
.page-banner .left:after {
content: "Background text";
position: absolute;
top: 40%;
left: 35%;
z-index: -1;
}
Upvotes: 0
Reputation: 24702
We could use a transform
like so:
CSS
.page-banner-text {
top: 50%;
transform: translateY(-50%);
position: absolute;
}
More information on this technique.
Upvotes: 4
Reputation: 6387
What you can do is, set the text position to absolute. Then give it a top: 50%; and give it a top margin of minus half its height.
Upvotes: 1