2011-08-15 146 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

簡單而高效!謝謝! –