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

网站建设 2021-07-03 08:15www.dzhlxh.cn网站建设

复制代码
代码如下:

<!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>

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板