2011-08-15 148 views
4

视图上http://www.eveo.org
下载站点,方便修改:
http://www.eveo.org/backup/eveo.rar
http://www.eveo.org/backup/eveo.zip水平和垂直居中网站

正如你可以看到,现在,它的水平和垂直使用一个简单的表法中心:

<table cellpadding="0" cellspacing="0"> 
    <tr> 
     <td align="left"> 
     *put anything in here and it will be aligned horizontally and vertically 
     </td> 
    </tr> 
</table> 

accompanying CSS: 

table 
{ 
height: 100%; 
width: 100%; 
vertical-align: middle; 
} 

但是,在我的文档中我没有设置文档类型,我只有:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 

如果我添加一个标准的文档类型,如下列:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 

我的表的方法不再有效并不起作用。因此,无论浏览器窗口大小如何,我都需要一种新的方式来垂直和水平居中我的网页。

+0

看到http://stackoverflow.com/questions/396145/whats-the-best-way-of-centering-a-div-vertically -with-css? – Mat

回答

5

有一些不需要Javascript或黑客的跨浏览器解决方案。

一个很好的例子是here

看一看也this之一。

对于某些学习,请查看关于gtalbot的优秀example关于CSS中的水平对齐。

好运>)

+0

谢谢你!有问题垂直居中。 [第一个例子](http://www.infinitywebdesign.com/research/cssverticalcentereddiv.htm)很好,但我很困惑他们如何试图版权CSS ... – Wilf

+0

不适合我。将其大小调整为小于内容的高度。 – dude

2

您可以使用CSS/HTML来做到这一点,但是如果您的身高是已知的,或者您可以使用JavaScript来获取身高,我将要使用的方法将效果最佳。

HTML:

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="utf-8"> 
     <title>My Centered Page</title> 
    </head> 

    <body> 
     <div class="container"> 

      <!-- My Content will be 500px tall --> 

     </div> 
    </body> 
</html> 

CSS:

.container { height:500px; margin:-250px /* Half the height container */ auto; position:absolute; top:50%; width:960px; } 

的JavaScript(jQuery的):如果你不知道的高度,或者如果它的变化。

(function() { 

    var $container = $('.container'), 
     height = $container.outerHeight(); 

    $container.css({ 
     'marginTop': (height/2) * -1 
    }); 

})(); 
3

HTML

<div id="container"></div> 

CSS

div#container { 
    width: 200px; 
    height: 200px; 
    margin-left: -100px; /* Half of width */ 
    margin-top: -100px; /* Half of height */ 
    position: absolute; left: 50%; top: 50%; 
} 
+0

简单而高效!谢谢! –