代码改变世界

图片在div中居中对齐

2014-06-09 16:29  南言北兼  阅读(448)  评论(0编辑  收藏  举报

通过在图片后面加一个隐藏span间接实现img居中,

代码如下:

<style type="text/css"> 
   div{ border:1px solid #ccc; height:500px; width:500px; text-align:center; margin:0 auto; background:#ccc;} 
   img{ vertical-align:middle; } 
   div span{ height:100%; width:0; overflow:hidden; display:inline-block; vertical-align:middle; } 
</style>
<div class="test">
<img src="icon.png"><span> </span>
</div>


还有一种方式,借助table布局:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
*{ margin:0; padding:0;}
    #box{
            width:500px;height:400px;
            text-align:center;
            border:1px solid #d3d3d3;background:#fff;

            display: table;
            *display:block;
            *font-size:349px;  // 字体大小约为容器高度的0.873倍 400*0.873 = 349 
            *font-family:Arial;   // 防止非utf-8引起的hack失效问题,如gbk编码 
    }

    #box span{
            display: table-cell; vertical-align:middle;
    }
    #box img{
            *vertical-align:middle;
    }
</style>
</head>

<body>
    <div id="box">
        <span><img src="http://www.w3cfuns.com/resource/images/extend/logo/w3cfuns_logo_hd.png" width="420" height="300" alt="" /></span>
    </div>
</body>
</html>