div 图片垂直居中

div水平居中很容易,设置css样式 text-align: center;  就可以了。

垂直居中也有个属性 vertical-align: middle; 这个属性普通设置是没有效果的。

第一种方法:通过一个空白图片可以达到垂直居中的效果。

<html>
    <style>
    #image{ 
        width:500px;
        height:500px;
        background:#fff000;
        text-align: center;
        overflow: hidden;
    }
    #image img {
    vertical-align: middle;
   }
    #block {
        width: 0px;
        height: 100%;
    }    
    </style>
    <body>
        <div id="image">
            <img src="http://www.mm21.cn/dimg6/qqtu/201105/20110507234620615.jpg"/>
             <img src="" id="block"/>
        </div>
    </body>
</html>

 

 个人觉得vertical-align: middle 是相对于左边的高度垂直居中的,我给左边一个填满div的图片,就可以实现垂直居中了。

第二种方法:往div里面加表格。

<html>
    <style>
#a {
    background: #fff000;
    width: 500px;
    height: 500px;
    overflow: hidden;
    text-align: center;
}
</style>
    <body>
        <div id="a">
            <table width="100%" height="100%">
                <tr>
                    <td align="center">
                        <img src="http://static.cnblogs.com/images/logo_small.gif" />
                    </td>
                </tr>
            </table>
        </div>
    </body>
</html>

 在表格里就很容易设置居中了。

经测试,这两种做法都没有浏览器不兼容的问题。推荐用第一种方法。

另外,说一下overflow: hidden; 这个属性,当图片大小超出div的大小时,会影藏超出的部分。不设置的话,图片会全部显示,覆盖在div上。 

 

posted @ 2012-07-03 23:15  垚淼  阅读(8646)  评论(2编辑  收藏  举报