CSS设置未知大小图片在已知大小容器水平垂直居中

内容摘要
复制代码代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.o
文章正文

复制代码
代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cn" >
<head>
<title>未知大小图片在已知大小容器水平/垂直居中</title>
<style type="text/css">
.box {
/*非IE的主流浏览器识别的垂直居中的方法*/
display: table-cell;
vertical-align:middle;
/*设置水平居中*/
text-align:center;
/* 针对IE的Hack */
*display: block;
*font-size: 175px;/*约为高度的0.873,200*0.873 约为175*/
*font-family:Arial;/*防止非utf-8引起的hack失效问题,如gbk编码*/
width:200px;
height:200px;
border: 1px solid #EEE;
float:left;
}
.box img {
/*设置图片垂直居中*/
vertical-align:middle;
}
</style>
<body onload="int()">
<div class="box">
<img src="http://www.baidu.com/img/baidu_logo.gif" />
</div>
<div class="box">
<img src="http://bbs.blueidea.com/images/default/logo.gif" />
</div>
<div class="box">
<img src="http://www.baidu.com/img/baidu_logo.gif" />
</div>
<div class="box">
<img src="http://bbs.blueidea.com/images/default/logo.gif" />
</div>
<div class="box">
<img src="http://www.baidu.com/img/baidu_logo.gif" />
</div>
<div class="box">
<img src="http://bbs.blueidea.com/images/default/logo.gif" />
</div>
<div class="box">
<img src="http://www.baidu.com/img/baidu_logo.gif" />
</div>
<div class="box">
<img src="http://bbs.blueidea.com/images/default/logo.gif" />
</div>
<div class="box">
<img src="http://www.baidu.com/img/baidu_logo.gif" />
</div>
<div class="box">
<img src="http://bbs.blueidea.com/images/default/logo.gif" />
</div>
<script language="javascript">
<!--
function int(){
obj=document.getElementsByTagName("img");
for(var i=0;i<obj.length;i++){
imgnum=obj[i];
size(imgnum);
}
}
function size(_imgnum){
w=parseInt(_imgnum.offsetWidth);
h=parseInt(_imgnum.offsetHeight);
s=w/h;
if(w>200){
w=200;
h=200/s;
_imgnum.style.width=w+"px";
_imgnum.style.height=h+"px";
}
if(h>200){
h=200;
w=200*s;
_imgnum.style.width=w+"px";
_imgnum.style.height=h+"px";
}
}
//-->
</script>
</body>
</html>

代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!