CSS cross browser vertical align

I finally got tired of living without cross browser vertical align property in css and after a bit of searching and trying a few different methods here is the one that I went with in the end. It requires some ie only styles which isn’t ideal but it gets the job done.

In this instance I wanted to center (vertical and horizontally) an image inside a div 80px by 80px - the image was being resized by server side code and I knew that no side would be longer than 80px;

The fix revolves around using table positioning in Firefox, Safari and Opera and relative positioning voodo in Internet Explorer.

html:

<div class='thumbnail'><div class='img_wrapper'><img src='....' /></div></div>

css:

.thumbnail {width:80px;	height:80px; text-align:center;	display:table;}
.thumbnail .img_wrapper { display:table-cell; vertical-align:middle; }

ie-only css:

.thumbnail {position:relative;}
.thumbnail .img_wrapper { position:absolute; top:50%; left:0px; }
.thumbnail .img_wrapper img { position:relative; top:-50%; }

use your favourite method for applying ie only styles- I prefer ie only stylesheets

<!--[if IE]>
<link rel="StyleSheet" href="/css/ie-style.css" type="text/css" media="screen"/>
<![endif]-->

Leave a Reply