图片或文字或box垂直居中

1,text-align:center可以使文字图片等行内元素居中,margin:auto;只能使块元素左右居中

2,line-height:100%/1;当前字体尺寸相乘来计算行间距,可以设置line-height:外框高度使文字上下居中

3,要使图片居中,必须设置图片vertical-align: middle;

(1):设置*font-size: 框高*0.873;可以使ie6下的图片上下居中;

(2):增加一个span空标签,添加font-size:0主要是考虑部分浏览器会对换行和空格产生一个“字符”做处理

<style type="text/css">
.test_box {
    width: 300px;
    height: 300px;
    /*line-height: 300px;*/
    border: 1px solid #333;
    *font-size:262px;
    font-size:0;
    overflow:hidden;
    text-align:center;
    float: left;
    vertical-align: middle;
}
.test_box .hook {display:inline-block;width:0;height:100%;overflow:hidden;margin-left:-1px;font-size:0;line-height:0;vertical-align:middle;}
</style>
    <div class="test_box">
    <span class="hook"></span>
    <a href="http://blog.linxz.de/css_book/" target="_blank"><img src="http://image.zhangxinxu.com/image/study/s/s128/mm1.jpg" alt="" /></a>
</div>
View Code

(3):用table td 设置text-align: center; vertical-align: middle;使图片垂直居中

(4):用div设置 display: table-cell;使图片垂直居中,但是ie6,7不支持

原文地址:https://www.cnblogs.com/55555azhe/p/3468077.html