需要说明的是,如果你想用这个方法使整个页面要居中,建议不要套在一个DIV里,你可以依次拆出多个div,只要在每个拆出的div里定义MARGIN-RIGHT: auto;MARGIN-LEFT: auto; 就可以了。
实例
代码如下
复制代码
<style type="text/css">
body { margin: 0; padding: 0; background: #1d1d1d; font-size: 10px; font-family: Verdana, Arial, Helvetica, sans-serif; }
h1 { font: 4em Georgia, "Times New Roman", Times, serif; color: #fff; border-bottom: 5px dotted #999; margin: 0; padding: 0 0 10px; }
h1 span { font-weight: bold; display:block; font-size:1.5em; color: #fff000; }
.vert { width: 580px; height: 190px; position: absolute; top: 50%; left: 50%; margin: -95px 0 0 -290px; }
</style>
html代码
<div class="vert">
<h1>www.111cn.net<span>CSS让DIV垂直居中</span></h1>
</div>
例2
<html>
<head>
<style>
body{TEXT-ALIGN: center;}
#center{ MARGIN-RIGHT: auto;
MARGIN-LEFT: auto;
height:200px;
background:#F00;
width:400px;
vertical-align:middle;
line-height:200px;
}
</style>
</head>
<body>
<div id="center"><p>test content</p></div>
</body>
</html>
说明:
vertical-align:middle;表示行内垂直居中,我们将行距增加到和整个DIV一样高line-height:200px;然后插入文字,就垂直居中了。
还有一种解决办法
以下为让div显示在浏览器正中间的样式
代码如下
复制代码
<style type="text/css">
#centerdiv {
position:absolute; <!--这个属性是设置div以绝对位置显示-->
top:50%;<!--在离顶部50%的位置显示-->
left:50%;<!--在离左边50%的位置显示-->
margin:-150px 0 0 -100px;<!--这个设置大家开始一看,可能觉得好像不是很明白,在下面为大家详细讲解-->
width:300px;
height:200px;
background:black;
}
</style>
相信大家最不明白就是在margin:-150px 0 0 -100这个属性上面,在不设置这个属性的时候,这个div的x坐标为内容显示部分的50%,y坐标为内容显示部分的50%,显示出来的然而这样的话只能说这个div的起点是在正中间,我们需要的是将整个div显示在正中间,所以给margin-left:-150px;(这里的150是从width属性中得来的它是等于width的一半,对应的margin-top也是通过通样的方法得来的。)这样就会把整个div的宽度分一半到左边就可以让其水平居中了,在设置margin-top:-100px;是同样的道理,会将整个div的高度分一半到上面显示。就形成了整个div在浏览器的正中间显示。