Search code examples
cssvertical-alignment

Vertical aligning text in overlay of image


Having some trouble getting the desired effect on an image overlay with responsive image. What I want is upon hovering over the image, the colour block and text to appear as shown, but for the text to be in the vertical centre of the div. I have tried vertical-middle but it doesn't seem to be working. Can't make the width and height set value as need to collapse and expand. If anyone can help i'd appreciate it. Thanks

Code, CSS below

.overlay-box {
   position: relative;
}
.overlay {
  display: none;
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   background-color: rgba(38,150,198,0.5);
}
.overlay p {
   color: #ffffff;
   text-align: center;
}
.overlay-box:hover .overlay {
     display: block;
}
<div class="row">
  <div class="col-xs-12 col-sm-4 col-md-3" style="margin-bottom: 20px;">

      <div class="overlay-box">
            <a href="#" target="_blank">
              
                   <div class="overlay">
                   
                          <p>1st line<br>2nd line<br><br>
                          3rd line</p>
                   </div>
                <img src="http://placehold.it/2000x2000" class="img-responsive "/></a>


      </div>

  </div>

  </div>


Solution

  • You need to wrap the overlay with another div(since tables seem to ignore their height and width when they're absolute) and add position:absolute to it. Then add dislpay:table and dislpay:table-cell; vertical-align:middle for the child divs.

    Check out this fiddle: https://jsfiddle.net/65cvzcev/