2011-08-27 31 views
4

如何將頁面內容居中放置,使其以每種屏幕大小爲中心?例如,如果我調整了我的瀏覽器的Allegorithmic,則中心內容將向左移動,直到它到達瀏覽器窗口。有某些背景元素無限地水平延伸(頂部爲深灰色,中間爲淺灰色等)。我可以在我的筆記本電腦和iMac上打開此網站,並將其集中。我認爲我可能會使用絕對定位來將內容從左側移動x像素,但這不起作用,因爲以小屏幕爲中心的300像素不會將其集中在大屏幕上。HTML/CSS內容始終居中

因此,本質上我想重複Allegorithmic網站的功能,具有橫向無限的背景,但有某些內容始終保持「居中」。

回答

5

如果你想要元素總是居中使用margin: 0 auto;在它的樣式。

#yourElement{ 
    margin: 0 auto; 
} 

W3.org reference for centering things using CSS

要獲得背景元素,以延長整個頁面長度只給他們100%的寬度,然後進行內部的子容器,並給他們相同的樣式以上。我敢打賭,你給出的例子只是用一個高度爲1px的線條在背景上看起來。

Example

Example with image bg

標記

<div id="background"> 
    <div id="content"> 
    </div> 
</div> 

CSS

#background{ 
    width: 100%; 
} 
#content{ 
    width: 960px; 
    margin: 0 auto; 
} 
0

試試這個 -

.center{ 
    margin: 0 auto; 
    position: relative; 
} 

auto應該對齊頁面內容根據瀏覽器的尺寸調整到中心留下的空間(左,右)。

0

您可以爲每個「級別」定義內部div的容器。

<div id="first" class="container"><div class="inner"> 
    first content goes there 
</div></div> 
<div id="second" class="container"><div class="inner"> 
    another content goes there 
</div></div> 
... 
... 
... 

,並與CSS樣式它,使用ID爲每個容器自定義樣式(這些都是100%的寬度,使他們有充分的BG)

.container { 
    background: red; 
    text-align: center; 
} 
.container > .inner { 
    margin: 0 auto; 
    width: 960px; 
    text-align: left; 
} 
0

HTML

<div id="wrapper"> 
    <header> 
     <nav> 
     .... 
     </nav> 
    </header> 

    <div id="main"> 
     ..... 
    </div> 
</div> 

CSS

#wrapper { 
    width: 960px /* whatever you wanted but there has to be a width*/ 
    margin: 0 auto; 
} 

這會包裹一個以你的頁面的全部內容爲中心。

希望這會有所幫助。