css不确定高度设置垂直居中二种方法

发布时间:2019-12-09编辑:脚本学堂
css中不确定高度时设置垂直居中的两种方法,两个兼容性强的垂直居中的代码,感兴趣的朋友参考下。

实现css样式效果:
不确定高度的垂直居中,两个兼容性强的垂直居中的代码。

例1,不确定高度垂直居中。
 

复制代码 代码示例:
/* center < */
.vetically {
vertical-align: middle;
display: table-cell;
*position: relative;
}
.vetically_C {
display: block;
margin: 0 auto;
text-align: center;
*position: absolute;
*top: 50%;
*left: 50%;
*margin-top: expression(-(this.height ) / 2);
*margin-left: expression(-(this.width ) / 2);
}
/* center > */

例2,标准浏览器的情况还是和上面一样,不同的是针对IE6/IE7利用在img标签的前面插入一对空标签的办法。
 

复制代码 代码示例:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>方法2 - 未知高度的图片垂直居中 - www.osxue.com</title>
<style type="text/css">
body {
height:100%;
}
#box{
width:500px;height:400px;
display:table-cell;
text-align:center;
vertical-align:middle;
border:1px solid #d3d3d3;background:#fff;
}
#box img{
border:1px solid #ccc;
}
</style>
<!--[if IE]>
<style type="text/css">?
#box i {
display:inline-block;
height:100%;
vertical-align:middle
}
#box img {
vertical-align:middle
}
</style>
<![endif]-->
</head>
<body>
<div id="box">
<i></i><img src="images/demo_zl.png" alt="" />
</div>
</body>
</html>