众所周知,图片的水平居中比较简单,但是图片的垂直居中比较麻烦一些,今天查阅了资料并自己写了测试代码,来实现兼容IE,FF,chrome等主流浏览器的图片在div中的垂直居中的方法。
css样式代码如下:
<style type="text/css">
*{
margin: 0;
padding: 0
}
div {
width: 210px;
height: 210px;
}
.attention {
color: red;
font-weight: bold;
}
.example1 {
background: blue;
}
.example2 {
background: green;
display: table-cell;
vertical-align: middle;
}
.example2 img {
vertical-align: middle;
}
.example3 {
background: yellow;
display: table-cell;
vertical-align: middle;
*font-size: 183px;
}
.example3 img {
vertical-align: middle;
}
</style>
*{
margin: 0;
padding: 0
}
div {
width: 210px;
height: 210px;
}
.attention {
color: red;
font-weight: bold;
}
.example1 {
background: blue;
}
.example2 {
background: green;
display: table-cell;
vertical-align: middle;
}
.example2 img {
vertical-align: middle;
}
.example3 {
background: yellow;
display: table-cell;
vertical-align: middle;
*font-size: 183px;
}
.example3 img {
vertical-align: middle;
}
</style>
然后html代码如下:
<
h3
>图片在div中正常显示,例子中div的尺寸均为210px*210px,图片为210px*158px
</
h3
>
< p class ="attention" >这里为了专门验证DIV中的图片垂直居中,特地将DIV的宽度设置成同图片宽度一样;图片的水平居中较简单,可以设置div{text-align:center} </ p >
< div class ="example1" >
< img src ="http://img01.taobaocdn.com/bao/uploaded/i1/T1FOl6XghEXXcn5fYb_094058.jpg_210x210.jpg" />
</ div >
< h3 >图片在div中居中显示,设置div{display:table-cell;vertical-align:center} div img {vertical:middle} </ h3 >
< p class ="attention" >在IE8,chrome18,firefox12下测试通过,IE6/7均不通过 </ p >
< div class ="example2" >
< img src ="http://img01.taobaocdn.com/bao/uploaded/i1/T1FOl6XghEXXcn5fYb_094058.jpg_210x210.jpg" />
</ div >
< h3 >图片在div中居中显示,设置IE hack,加上一句 *font-size:183px来hack </ h3 >
< p class ="attention" >183 = 210*0.875,为什么乘这个0.875,原理不知,有待补充,目前由前人经验得来。IE6/7也能通过。 </ p >
< div class ="example3" >
< img src ="http://img01.taobaocdn.com/bao/uploaded/i1/T1FOl6XghEXXcn5fYb_094058.jpg_210x210.jpg" /> </div>
< p class ="attention" >这里为了专门验证DIV中的图片垂直居中,特地将DIV的宽度设置成同图片宽度一样;图片的水平居中较简单,可以设置div{text-align:center} </ p >
< div class ="example1" >
< img src ="http://img01.taobaocdn.com/bao/uploaded/i1/T1FOl6XghEXXcn5fYb_094058.jpg_210x210.jpg" />
</ div >
< h3 >图片在div中居中显示,设置div{display:table-cell;vertical-align:center} div img {vertical:middle} </ h3 >
< p class ="attention" >在IE8,chrome18,firefox12下测试通过,IE6/7均不通过 </ p >
< div class ="example2" >
< img src ="http://img01.taobaocdn.com/bao/uploaded/i1/T1FOl6XghEXXcn5fYb_094058.jpg_210x210.jpg" />
</ div >
< h3 >图片在div中居中显示,设置IE hack,加上一句 *font-size:183px来hack </ h3 >
< p class ="attention" >183 = 210*0.875,为什么乘这个0.875,原理不知,有待补充,目前由前人经验得来。IE6/7也能通过。 </ p >
< div class ="example3" >
< img src ="http://img01.taobaocdn.com/bao/uploaded/i1/T1FOl6XghEXXcn5fYb_094058.jpg_210x210.jpg" /> </div>
有问题可以给我留言!