Vertically Center Align Image inside DIV – Responsive Alignment

Vertically Center Align Image inside the div is bit tricky you need to write up some HTML and CSS. Learn how to Vertically Center Align Image inside the div element.

Vertical alignment of any image in any of the div is bit tricky because using padding give you headache on media device change. Like you give 50% padding and after that you change the device then it will move the image aside according to your device. In this tutorial you will learn how to Vertically center align image inside DIV element.

Without the use of Framework like Twitter Bootstrap, Foundation etc you can make your image vertically center aligned and get rid of extra padding and margins. Thanks to Hashem Qolami who write up this code. Understanding how you can vertically center aligned an image inside the DIV.

Vertically Center Align Image.

HTML Code:

<div class="responsive-container">
     <div class="dummy"></div>

    <div class="img-container">
        <img src="http://placehold.it/150x150" alt="" />
    </div>
 </div>

 

CSS Code:

.responsive-container {
 position: relative;
 width: 100%;
 border: 1px solid black;
 }

.dummy {
 padding-top: 100%; /* forces 1:1 aspect ratio */
 }

.img-container {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;

text-align:center; /* Align center inline elements */
 font: 0/0 a;
 }

.img-container:before {
 content: ' ';
 display: inline-block;
 vertical-align: middle;
 height: 100%;
 }

.img-container img {
 vertical-align: middle;
 display: inline-block;
 }

 

Live Example:

Check out the live working Demo Fiddle of Vertically Center Align Image inside DIV. Learn more other tricks of  HTML & CSS. We have a Web Design section full of these types of Tutorials and tips to shine your website.

Leave a Reply

Your email address will not be published. Required fields are marked *