How to vertically align an image within a div. Again.

Posted by Maciej KoƂodziej Fri, 25 Jan 2008 11:44:00 GMT

Yeah, so the topic is old, all right. One can find hundreds of articles on the web. Nevertheless, I spent a few hours yesterday looking for an elegant and simple solution to this problem.

I wanted to:

  • center an image of an unknown size (but of known maximum size) within a div element
  • simple implementation in pure CSS, no tables
  • cross-browser compatibility on all major browsers

I found one solution on Webmaster World forum. It worked on IE, but not in Firefox. After some more research I added a hack proposed by Nicholas Gagne and now it seems to work on both browsers:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <style type="text/css">
    div {line-height:150px; text-align: center; width: 150px; 
         font-size: 150px;}
    img {vertical-align:middle;}
    *>div{font-size:12px;}
    </style>
  </head>
  <body>
    <div style="border:1px solid gray;">
      <img src="/images/examples/test.jpg">
    </div>
  </body>
</html>

Pay attention to the DOCTYPE declaration: it has to be strict XHTML. It doesn’t work with transitional in Firefox. You can replace the line-height, width and font-size of course, just keep the “vertical” pixel sizes the same - width can be different.

I tested it in IE6 and Firefox 2.0.0.11