返回顶部

收藏

图片水平居中兼容IE6、7、8和FF

更多

[CSS]代码

<!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">
.box {
    display: table-cell;
    vertical-align:middle;
    text-align:center;
    *display: block;
    *font-size: 175px;  /*高度/字体大小的比值为1.14*/
    *font-family:Arial;
    width:200px;
    height:200px;
    border: 1px solid #ccc;
    padding:3px;
    overflow:hidden; /*防止用js缩放时出现不及时*/
}
.box img{
    vertical-align:middle; border:0;
}
</style>
<script language="javascript">
var flag=false;
function DrawImage(ImgD,w,h){
    var image=new Image();
    image.src=ImgD.src;
    if(image.width>0 && image.height>0){
        flag=true;
        if(image.width/image.height>= w/h){
            if(image.width>w){
              ImgD.width=w;
              ImgD.height=(image.height*w)/image.width;
            }else{
              ImgD.width=image.width;
              ImgD.height=image.height;
            }
        }else{
            if(image.height>h){
              ImgD.height=h;
              ImgD.width=(image.width*h)/image.height;
            }else{
              ImgD.width=image.width;
              ImgD.height=image.height;
            }
        }
    }
}
</script>
</head>

<body>

<div class="box">
    <img src="http://img.bbs.163.com/new/20111012/photo/go/gogo911@vip.163.com/95ea49bc830405a6481faed4ba98b1b8.jpg" onload="DrawImage(this,200,200);" />
</div>

<hr />

<div class="box">
    <img src="http://img.bbs.163.com/new/20111012/photo/go/gogo911@vip.163.com/7f94f4d589c952dd6cc267da2d4cb80e.jpg" onload="DrawImage(this,200,200);" />
</div>

</body>
</html>

标签:css,html

收藏

0人收藏

支持

0

反对

0