div代码居中 上下居中 左右居中

来源:互联网 发布:windows 能用final cut 编辑:程序博客网 时间:2024/04/30 22:07

<!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=gb2312" />
<title>Universal vertical center with css</title>
<style>
#outer {
height:300px;
width:300px;
overflow:hidden;
position:relative;
text-align:center;
}
#outer[id]{
display:table;
position:static;
}
#middle{
position:absolute;
top:50%;
}
/* for explorer only*/
#middle[id]{
display:table-cell;
vertical-align:middle;
position:static;
}
#inner{
position:relative;
top:50%;
}
/* for explorer only*/
/* optional : #inner[id] {position:static}*/
.withBorder{
border:1px green solid;
}
</style>
</head>

<body>
<div id="outer" class="withBorder">
<div id="middle">
<div id="inner">
<img src="http://blog.163.com/lixiaofengfly@126/blog/image/guest_test_icon2.jpg"/>
<!-- any text any height any content,
everthing is vertically centered.
或者文字也可以
只需要设置 outer 的 高度 宽度 就可以得到想要的效果了
其他... 复制!
-->
</div>
</div>
</div>
</body>
</html>



精简后的代码

<!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=gb2312" />
<title>Universal vertical center with css</title>
<style>

#outer {
height:300px;
width:300px;
display:table-cell;
vertical-align:middle;/*火狐,chrom垂直居中*/
line-height:300px; /*IE7垂直居中*/
text-align:center; /*水平居中*/
}
.withBorder{
border:1px green solid;
}
</style>
</head>

<body>
<div id="outer" class="withBorder">
<img src="http://blog.163.com/lixiaofengfly@126/blog/image/guest_test_icon2.jpg"/>
</div>
</body>
</html>

原创粉丝点击