2009-08-28 37 views
0

我無法讓我的網站以CSS爲中心。我已經嘗試了所有的網絡,包括各地提出的常用方法:無法獲得CSS元素居中

body { 
    text-align: center; 
} 
#container { 
    width: 770px; 
    margin: 0 auto; 
    text-align: left; 
} 

然後使用

<div id="container> 
<!-- Centered Content Goes here--> 
</div> 

,但它只是不會去市中心。它停留在頁面的左側。

的CSS的,我想爲中心元素的一個例子是這樣的:

#topHeader 
{ 
    background:url(images/top_header.jpg); 
    position:absolute; 
    width: 695px; 
    height: 242px; 
    top: 0px; 
    left: 0px; 
} 

所以,我的HTML應該是這樣的:

<div id="container> 
<div id="topHeader></div> 
<!-- All other elements go here as well--> 
</div> 

但正如我之前提到的,該元素保持放置。 謝謝! 埃裏克

回答

0

主要問題是您的#topHeader元素的絕對定位。因爲您已將它完全放在top: 0px; left: 0px;的位置,這正是它將要定位的位置 - 位於頁面的左上角。

#topHeader元素中刪除絕對位置開始。

-2

據我所知,它根本不起作用。 text-align以文本或內聯內容爲中心,而不是塊元素。

編輯:另一方面,粉碎機的鏈接是有道理的。不幸的是,只有固定大小的塊。

+0

深紅色,你不能在不知道其寬度的情況下居中塊元素。 –

0

您將標題絕對放置,因此它與包含的塊(即body)偏移,而不是父元素。你想要的是相對定位。

絕對

的框的位置(以及可能的尺寸)與 '頂部', '右', '底部',和 '左' 屬性指定。這些屬性指定 相對於框的 包含塊的偏移量。絕對的 定位框取出 正常流程。這意味着他們沒有 影響後面的 兄弟姐妹的佈局。此外,雖然絕對定位盒子有邊距,但他們做的 不會與任何其他邊距合攏。

- 9.3.1 Choosing a positioning scheme: 'position' property

絕對:

<html> 
    <head> 
     <style type="text/css"> 
      body { 
       text-align: center; 
      } 
      #container { 
       color:blue; 
       border:1px solid blue; 

       width: 770px; 
       margin: 0 auto; 
       text-align: left; 
      } 
      #topHeader 
      { 
       color:red; 
       border:1px solid red; 

       position:absolute; 
       width: 695px; 
       height: 242px; 
       top: 0px; 
       left: 0px; 
      }  
     </style> 
    </head> 
    <body> 
     outside 
     <div id="container"> 
      inside 
      <div id="topHeader">deep inside</div> 
      <!-- All other elements go here as well--> 
     </div> 
    </body> 
</html> 

相對:

<html> 
    <head> 
     <style type="text/css"> 
      body { 
       text-align: center; 
      } 
      #container { 
       color:blue; 
       border:1px solid blue; 

       width: 770px; 
       margin: 0 auto; 
       text-align: left; 
      } 
      #topHeader 
      { 
       color:red; 
       border:1px solid red; 

       position:relative; 
       width: 695px; 
       height: 242px; 
       top: 0px; 
       left: 0px; 
      }  
     </style> 
    </head> 
    <body> 
     outside 
     <div id="container"> 
      inside 
      <div id="topHeader">deep inside</div> 
      <!-- All other elements go here as well--> 
     </div> 
    </body> 
</html> 
5

與此 dead centre

+0

+1,我喜歡這個主意。 –

+0

令人敬畏的例子。將它添加到我的CSS技術作弊列表中。 –

+0

+1好資源。 –

0

嘗試增加這喲頂端試你的css文件:

// Wipes out any preexisting padding and margin. 
html, body { 
    padding: 0; 
    margin: 0; 
} 

然後添加一個位置:relative;指導你想要中心的課程。實際上,可以嘗試將它添加到HTML中,以便所有類都使用相對位置。這可能是你有位置:絕對;設置,然後結合左:0px;強制你的頭部包含忽略邊距:0 auto;並留在頁面的左側。

0

嘗試所有這些居中方法時要檢查的一件事是確保您的文檔類型對於正在使用的方法是正確的。

希望這對你有幫助。