【from】http://bbs.blueidea.com/thread-2666987-1-9.html 我想应该有很多朋友都会碰到DIV中图片垂直居中的问题,DIV不像TABLE,直接一个valign就搞定,特别是当图片的大小不确定的时候,无法通过事先定位来解决。而等比缩放的话,IE6中不认 max-height跟max-width。 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> .box { /*非IE的主流浏览器识别的垂直居中的方法*/ display: table-cell; vertical-align:middle; /*设置水平居中*/ text-align:center; /* 针对IE的Hack */ *display: block; *font-size: 175px;/*这个值大概为最大高度的0.875*/ *font-family:Arial;/*防止非utf-8引起的hack失效问题,如gbk编码*/ width:200px; height:200px; border: 1px solid #eee; } .box img { /*设置图片垂直居中*/ vertical-align:middle; /*非IE6下的等比缩放*/ max-height:150px; max-width:150px; /*IE6下的等比缩放,注意expression其实是运行了一个JS程序,所以如果图片很多的话会引起CPU占用率高*/ width:expression(this.width >150 && this.height <= this.width ? 150: true); height:expression(this.height > 150 && this.width <= this.height ? 150 : true); } </style> </head> <body> <div class="box"><img src="02.jpg" /></div> </body> </html> 垂直居中2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>利用定位来显示垂直局中的图片</title> <style type="text/css"> .miao{width:170px;height:100px;display:table;text-align:center;border:solid 1px red;} .miao span{display:table-cell;vertical-align:middle;border:solid 1px blue;} .miao span img{border:dashed 1px green;} </style> <!--[if lte IE 7]> <style type="text/css"> .miao{position:relative;overflow:hidden;} .miao span{position:absolute;left:50%;top:50%;} .miao span img{position:relative;left:-50%;top:-50%;} </style> <![endif]--> </head> <body> <h1>固定高宽的容器中,图片垂直局中。</h1> <div class="miao"> <span><img src="http://bbs.blueidea.com/images/default/logo.gif" alt="Logo" /></span> </div> <hr /> <div class="miao" style="width:300px;height:80px;"> <span><img src="ttp://bbs.blueidea.com/images/default/logo.gif" alt="Logo" /></span> </div> <hr /> <div class="miao" style="width:500px;height:220px;"> <span><img src="http://www.google.cn/intl/zh-CN/images/logo_cn.gif" alt="Google" /></span> </div> </body> </html>