Thursday, June 13, 2013

Align image vertically middle

I'm here again after a long interval :)

I can't stop to share this knowledge because I have been searching for long time to find a solution to this problem.

I have faced many situations where I had to vertical align middle an image in a container. I had only 2 choices:

1) Using a table as suggested here: which will increase the amount of HTML and in turn increase the size of the page and make the page load slow. This could be too expensive if we have many images to be placed like this in the same page.

2) Set image as the background of the container like this:

<div style="background-image:url(img.jpg)" ></div>

and add the style

"background-position50% center;". 

Since it is not a good practice to give inline style, this idea was also not good.

And finally, I found a better and easy solution to this problem :)


Set the height and line-height of the container to same value (the maximum possible height of the image).
And add the style vertical-align: middle to the image.


(Assume that image height will not increase 100px)


<div class="img_container">
    <img alt="image" src="img.jpg" />

    height: 100px; // set height as the maximum possible height of the image
    line-height: 100px; // set line-height same as height
.img_container img
    vertical-align: middle;

This worked for me like a charm.

Idea reference:

Hope you enjoyed the post.
Thanks for reading :)

No comments:

Post a Comment