图片(未知高度)div中垂直居中对齐css

在曾经的 淘宝UED 招聘 中有这样一道题目:
至于如何解决,下面是一个权衡的相对结构干净,CSS简单的解决方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.box {
/*非IE的主流浏览器识别的垂直居中的方法*/
display: table-cell;
vertical-align:middle;

/*设置水平居中*/
text-align:center;

/* 针对IE的Hack */
*display: block;
*font-size: 175px;/*约为高度的0.873,200*0.873 约为175*/
*font-family:Arial;/*防止非utf-8引起的hack失效问题,如gbk编码*/

width:200px;
height:200px;
border: 1px solid #eee;
}
.box img {
/*设置图片垂直居中*/
vertical-align:middle;
}
1
2
3
<div class="box">
<img src="http://pics.taobao.com/bao/album/promotion/taoscars_180x95_071112_sr.jpg" />
</div>

当然还有其他的解决方法,在此不深究,有兴趣的可以阅读下:


1
2
3
4
5
6
7
8
9
10
11
12
.new_proimg{
 display: table-cell; /*非IE的主流浏览器识别的垂直居中的方法*/
 vertical-align:middle; /*非IE的主流浏览器识别的垂直居中的方法*/
 text-align:center; /*设置水平居中*/
 *display: block; /* 针对IE的Hack */
 *font-size: 104px; /*约为高度的0.873,120*0.873 约为104*/
 *font-family:Arial;  /*防止非utf-8引起的hack失效问题,如gbk编码*/
 width:120px;
 height:120px;
 margin-bottom: 5px;
 border: 1px solid #eee;
}

版本2

HTML代码:

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

CSS代码:

1
2
3
4
5
6
7
8
9
10
/*For Firefox Chrome*/
.demo{border:1px #dddsolid;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有这么一段:

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

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

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