必须指定高度,所以如果你在里面放动态的内容的话,后果会很糟糕滴~
HTML代码:
<div class="vert"> <h1>Hi, I''m<span>Vertically Aligned</span></h1> <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> </div>
CSS代码: 这种用绝对定位来实现的垂直居中,取决与元素的宽度和高度,你可以用下面这两个公式来计算元素的左边距和上边距
元素的宽度/2 = 负左边距 元素的高度/2 = 负上边距
在这个例子中,我们就是这么计算的
.vert { width: 580px; height: 190px; position: absolute; top: 50%; left: 50%; margin: -95px 0 0 -290px; }
完整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 10p |