Search code examples
cssvertical-alignmentmouseover

How do I align text vertically over a background image?


I am trying to overlay text with a white translucent background on an image when people mouse over that image. I found answers containing original type of the following code on here. Now I want to vertically align text to the middle of the image.

Is it possible?

HTML:

<div class="image">
    <img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div>

CSS:

.image {
    position:relative;
    width:400px;
    height:400px;
}
.image img {
    width:100%;
    vertical-align:top;
}
.image:after {
    content: 'Hello';
    color: #000000;
    vertical-align: middle;
    text-align: center;
    position: absolute;
    width:100%; 
    height:100%;
    top:0; 
    left:0;
    background: rgba(255,255,255,0.7);
    opacity:0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
}
.image:hover:after {
    opacity:1;
}

Solution

  • If the height of the image (or container) you are using is fixed, as in your example, then you can use a line-height method, as follows for the code in your example:

    .image:after {
        line-height: 400px;
    }
    

    Add that line to the .image:after selector, and it will achieve what you want.

    JSFiddle Example