• Follow me on:

Tuesday, September 6, 2011

How to vertical align an image in middle?

Many of us might have faced this problem of aligning an image in middle of a div.  I don't know about others but I used to use Padding-top in these situations.  But then if images are of different sizes i.e., of different heights then this padding-top doesn't seems to be the solution.  Then this css solved my problem. Normally these are situations when you are listing products and each of your image is of different size and you want them to be middle aligned in their respective DIV's.  Here's the HTML for the DIV where you have to place the image:


<div class="wraptocenter"><span></span><img src="banner_2.gif" alt="jaydharphics"></div>

And here's the CSS:

<style type="text/css">
.wraptocenter {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    height:200px;
    width:300px; border:10px solid #e4e4e4;
}
.wraptocenter * {
    vertical-align: middle;
}
/*******************************/
.wraptocenter {
    display: block;
}
.wraptocenter span {
    display: inline-block;
    height: 100%;
    width: 1px;
}
/******************************/
</style>
<!--[if lt IE 8]><style>
.wraptocenter span {
    display: inline-block;
    height: 100%;
}
</style><![endif]-->


I hope this was helpful to you. I hope Horizontal alignment is not a issue for you, if you still have problem with horizontal alignment then there are two usual methods one is "text-align:center;" and another is you can use margin:0 auto; for the image.

Share Your Solutions!!

No comments:

Post a Comment

All Rights Reserved Jaydharphics Click To Mail Me (+91 9564 5592 84)