关于运用css使div垂直居中

来源:百度知道 编辑:UC知道 时间:2024/07/04 08:19:38
代码如下:
<style type="text/css">
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
.Container {
position: absolute;
top: 0; left: 2px;
width: 352px;
height: 600px;
border-left: 1px dotted #CCCCCC;
border-right: 1px dotted #CCCCCC;
}
#Scroller-1 {
position: absolute;
overflow: hidden;
width: 352px;
height: 600px;
}
#Scroller-1 p {
margin: 0;
font-size: 11px;
text-indent: 20px;
color: #777;
}
.Scroller-Container {
background-color: #EEE;
}
.Scrollbar-Track {
width: 9px; height: 600px;
position: absolute;
top: 0px; left: 686px;
background-color: #EEE;
}
.Scrollbar-Handle {
position: absolute;
top: 0px; left: 0px;
width: 9px; height: 82px;
background-image:url(scroll.jpg);

.Container {
position: absolute;
top: 50%;/*把块的顶边定义在浏览器的中线上(此时并未居中)*/
left: 2px;
width: 352px;
height: 600px;
border-left: 1px dotted #CCCCCC;
border-right: 1px dotted #CCCCCC;
margin-top: -300px;/*把块的一半移动到中线以上实现居中*/
}

.Scroller-Container {
background-color: #EEE;
height: 140px;/*必须定义一个高度否则无法实现居中*/
position: absolute;/*此时的包含块是已经居中的Scroller-1,因为它是与Scroller-Container最近的定位的父元素,所以Scroller-Container得根据它来定位。Scroller-1已经居中很简单,是因为嵌套在Container中,且尺寸与Container一致。*/
top: 50%;/*把块的顶边定义在Scroller-1的中线上(此时并未居中)*/
margin-top: -70px;/*把块的一半移动到中线以上实现居中*/
}

简单说一下实现原理:要垂直居中,必须具备两个条件:一元素必须用定位使顶边定义在中线上;二元素必须有固定的高度,以便用负边距移动元素实现居中。

提点建议,其实兄弟你嵌套这么多层没有什么意义,像Scroller-1层和Scroller-Container 层完全可以去掉。

结构如下:
<body>
<div class="Container">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec iaculis, ante et congue feugia