Firefox中使用display: table-cell; vertical-align: middle;可以实现div垂直居中,而IE6/7中则需要借助IE6/7中css的特点实现垂直居中。为了实现Firefox和IE6/7兼容的垂直居中,还需要 借助于!important标记。Firefox支持!important标记,而IE6/7忽略!important标记,因此可以使用! important标记区别Firefox和IE6。(!important:提升指定样式规则的应用优先权。)
[示例代码-1]【上下布局-上下居中和左右居中】
<html>
<body>
<div style="display: table-cell; vertical-align: middle; height: 200px; border: 1px solid red;">
<p>垂直居中,Firefox only</p>
<p>垂直居中,Firefox only</p>
<p>垂直居中,Firefox only</p>
</div>
<div style=" margin-left:auto;margin-right:auto;border: 1px solid red;text-align:center;">
<p>垂直左右居中,IE6 and FF only</p>
<p>垂直左右居中,IE6 and FF only</p>
<p>垂直左右居中,IE6 and FF only</p>
</div>
<div style="border: 1px solid red; height: 200px; position: relative;">
<div style="position: absolute; top: 50%;">
<div style="position: relative; top: -50%;">
<p>垂直居中,IE6 only</p>
<p>垂直居中,IE6 only</p>
<p>垂直居中,IE6 only</p>
</div>
</div>
</div>
<div style="border: 1px solid red; height: 200px; position: relative; display: table-cell; vertical-align: middle;">
<div style="position: static !important; position: absolute; top: 50%;">
<div style="position: relative; top: -50%;">
<p>垂直居中,Firefox IE6 only</p>
<p>垂直居中,Firefox IE6 only</p>
<p>垂直居中,Firefox IE6 only</p>
</div>
</div>
</div>
</body>
</html>
[示例代码-2][左右布局]
<div style="relative;overflow:hidden;width:500px;height: 55px;border:2px solid #EFEFEF;background-color:#F3F3F3;">
<div style="float:left;margin:0 290 0 0px;width:161;border:green solid 0px;" >
<div style="border: 0px solid red; height: 50px; position: relative; display: table-cell; vertical-align: middle;padding-left:15px;">
<div style="position: static !important; position: absolute; top: 50%;">
<div style="position: relative; top: -50%;">
<img src="*src.jpg"/>
</div>
</div>
</div>
</div>
<div style="float:right;margin:0 0 10 -325px;padding-right:5px;padding-top:0px;width:325px;border:green solid 0px">
<div style="border: 0px solid red; height: 50px; position: relative; display: table-cell; vertical-align: middle;">
<div style="position: static !important; position: absolute; top: 50%;">
<div style="position: relative; top: -50%;">
<p>居中文字</p>
</div>
</div>
</div>
</div>
</div>