日期:2014-05-16  浏览次数:20857 次

如何实现css垂直居中

利用CSS让元素垂直居中是个很头疼的问题,这里就介绍两种简单实用的方法

方法一:利用行高(line-height)定位

line-height通常是用于调节一段文字的行与行之间的距离,或者说两行文字之间的距离,如果行高是500px,那么每一行中的文字距离本行的顶部就是250px,如果将文字的行高设为500px,并且外面的容器的高度也为500px,同样可以实现垂直居中,但是用它来实现垂直居中,也是有缺点的,就是如果内容过多,文字就会跑到下一行,那么内容就不可能垂直居中了。

HTML代码:

1.	<h1>Hi, I'm<span>Vertically Aligned</span> Within the H1</h1>

CSS代码:

1.	body {
2.	         margin: 0;
3.	         padding: 0;
4.	         background: #1d1d1d;
5.	         font-size: 10px;
6.	         font-family: Verdana, Arial, Helvetica, sans-serif;
7.	}
8.	h1 {
9.	         font: 3em Georgia, "Times New Roman", Times, serif;
10.	         color: #fff;
11.	         height: 500px;
12.	         line-height: 500px;
13.	         text-align:center;
14.	         border: 10px solid #999;
15.	}
16.	h1 span {
17.	         font-weight: bold;
18.	         font-size:1.5em;
19.	         color: #fff000;
20.	}
21.	p {
22.	         font-size: 1.3em;
23.	         color: #999;
24.	}
25.	strong {
26.	         color: #fff;
27.	}

方法二:利用绝对定位


先来看看效果,查看演示
这个方法有个缺点我必须指出,就是外面的块状元素,必须指定高度,所以如果你在里面放动态的内容的话,后果会很糟糕滴~

HTML代码:

1.	<div class="vert">
2.	        <h1>Hi, I'm<span>Vertically Aligned</span></h1>
3.	        <p>Abigo sudo mara paulatim odio, accumsan luptatum nibh nibh refero metuo opes ut fatua. Acsi et fere similis <strong>Using</strong> augue <strong>absolute</strong> validus. Regula <strong>positioning</strong> eu jus vel, indoles fere iaceo ea similis. Velit praemitto nulla vel luctus secundum. </p>
4.	</div>

CSS代码:

这种用绝对定位来实现的垂直居中,取决与元素的宽度和高度,你可以用下面这两个公式来计算元素的左边距和上边距

元素的宽度/2 = 负左边距
元素的高度/2 = 负上边距

在这个例子中,我们就是这么计算的

1.	.vert {
2.	        width: 580px;
3.	        height: 190px;
4.	        position: absolute;
5.	        top: 50%;
6.	        left: 50%;
7.	        margin: -95px 0 0 -290px;
8.	}

完整CSS代码

1.	body {
2.	        margin: 0;
3.	        padding: 0;
4.	        background: #1d1d1d;
5.	        font-size: 10px;
6.	        font-family: Verdana, Arial, Helvetica, sans-serif;
7.	}
8.	h1 {
9.	        font: 4em Georgia, "Times New Roman", Times, serif;
10.	        color: #fff;
11.	        border-bottom: 5px dotted #999;
12.	        margin: 0;
13.	        padding: 0 0 10px;
14.	}
15.	h1 span {
16.	        font-weight: bold;
17.	        display:block;
18.	        font-size:1.5em;
19.	        color: #fff000;
20.	}
21.	p {
22.	        font-size: 1.3em;
23.	        color: #999;
24.	}
25.	strong {
26.	        color: #fff;
27.	}
28.	.vert {
29.	        width: 580px;
30.	        height: 190px;
31.	        position: absolute;
32.	        top: 50%;
33.	        left: 50%;
34.	        margin: -95px 0 0 -290px;
35.	}




2楼lilongsheng11254天前 21:44
学习一下,调整页面的布局也是头疼的事。
1楼wwwwenhuan4天前 17:30
很基础,但也很重要