Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center text inside an absolutely-positioned div

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

Link to jsbin demo

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>
like image 917
farjam Avatar asked Aug 07 '14 14:08

farjam


2 Answers

We could use a transform like so:

Have a jsBin!

CSS

.page-banner-text {
    top: 50%;
    transform: translateY(-50%);
    position: absolute;
}

More information on this technique.

like image 187
misterManSam Avatar answered Oct 17 '22 12:10

misterManSam


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.

like image 20
almo Avatar answered Oct 17 '22 12:10

almo