Vertical Image Alignment Using CSS (Firefox and IE)
Thursday, November 2nd, 2006Here is a quick way to centre an image within a <div> box using only CSS (and using css expression for Internet Explorer).
<html> <head> <title>Vertical Image Alignment</title> <style type="text/css"> .content { width: 100px; height: 100px; display: table-cell; vertical-align: middle; text-align: center; border: 1px solid red; } .content img { margin-top: expression((100 - this.height)/2); } </style> </head> <body> <div class="content"> <img src="images/thumb3.jpg" /> </div> </body> </html>
The .content class creates a box of width 100×100 pixels. We set the display property to table-cell and take advantage of the vertical-align property available for table cell (this works in browsers such as Firefox) to center the image vertical in the box. Unfortunately, Internet Explorer versions up to 7 does not support display: table-cell. However, we can use dynamic CSS attributes to set the margin-top property of the image.
margin-top: expression((100 - this.height)/2);
The above code calculates the margin-top property to center vertically the image inside the box. The context of the this within the expression is the HTML element of the CSS selector.