纯CSS实现图片水平垂直居中于DIV,图片未知宽高

一个问题一直困扰着不少前端制作人员(也称前端开发工程师,o(∩_∩)o)。如题,如何实现一张未知宽高的图片在一个Div里面水平垂直居中呢?相信部分前端Sir首先想的是Table布局,是的,实现起来不是很麻烦,但肯定也有和浩子一样有代码洁癖的人。在这里,浩子忽略Table的实现方法,有兴趣的也可以去研究一下。下面介绍下用Html和CSS来实现如题效果。

先看看Demo效果:纯CSS实现图片水平垂直居中于DIV(图片未知宽高)

PS:你可以用Firebug或者任意浏览器的开发人员工具修改图片尺寸,测试测试效果。(任何关于本文的问题请留言

再看看代码,主要2部分:

HTML代码:

<div class=”demo”><a href=“#”><img src=“images/01.jpg” /></a></div>

CSS代码:

/*For Firefox Chrome*/

.demo{border:1px #ddd solid;width:208px;height:148px;overflow:hidden;text-align:center;display:table;float:left;margin:50px;position:relative;}

.demo a{display:table-cell;vertical-align:middle;width:200px;height:140px;}

.demo a img{border:1px #ddd solid;margin:0 auto;max-width:200px;max-height:140px;}

/*For IE7*/

*+html .demo a{position:absolute;top:50%;width:100%;text-align:center;height:auto;}

*+html .demo a img{position:relative;top:-50%;left:-50%;}

/*For IE6*/

*html .demo a{position:absolute;top:51%;width:100%;text-align:center;height:auto;display:block;}

*html .demo aimg{position:relative;top:-50%;left:-50%;width:expression(this.width>200?“200px”:“auto”);height:expression(this.height>140?“140px”:“auto”);}

其中For IE6中的css有这么一段:

width:expression(this.width>200?“200px”:“auto”);height:expression(this.height>140?“140px”:“auto”);

这是限制IE6下图片的最大宽和最大高,就像非IE6下的:

max-width:200px;max-height:140px;

是一个道理。

其他也没什么要过多解释的了,你懂的!如果你对部分CSS不太懂的话,请参考大前端的HTML+CSS一栏,或者前往w3school。