2011-10-06 61 views
-1

可能重複:
How to center DIV in DIV?如何居中div?

聽起來簡單,但無法弄清楚:

如何中心固定寬度的div在頁面上?

默認情況下,它向左。

halign已棄用,但我可以找到替換品。

[更新]

width:800px;left-margin:auto;right-margin:auto: 

的偉大工程。

有沒有辦法做到這一點,沒有設置固定的寬度?

+1

[這麼多重複](http://stackoverflow.com/search?q=center+div)。 – Alex

回答

2

試試這個:

<style> 
.centered { 
margin-left:auto; 
margin-right:auto; 
} 
</style> 

<div class="centered"> 
Some text 
</div> 
0
div { 
    margin-left: auto; 
    margin-right: auto; 
} 
1
<div style="margin:0 auto">content here</div> 
0

margin:auto;應該做的伎倆,我猜?

0

只要你有一個適當的doctype聲明,圍繞一個網頁div作爲應儘可能簡單:

#someDiv { 
    width: 624px; 
    margin-left: auto; 
    margin-right: auto; 
} 

如果你使用IE瀏覽器,你沒有一個DOCTYPE聲明(你'以怪癖模式運行),這是行不通的。解決方法是將適當的doctype聲明添加到您的頁面。你可以在這裏找到相應的聲明:

W3C QA - Recommended list of Doctype declarations you can use in your Web document

+0

什麼是合適的文檔類型? – evan

+0

@evan - 這一切都取決於您創建的文檔類型。 –

1

一個DIV,默認情況下,是整個頁面的寬度。

.mydiv 
{ 
    text-align: center; 
} 

OR

您可以通過執行該中心在div本身:您可以通過div的CSS設置爲居中內容

.mydiv 
{ 
    display: inline-block; /* make it be only as wide as its contents */ 
    margin: auto; /* centering magic by making the margins equal and maximum */ 
} 
0

有普遍做的兩種方式(我見過)。一個與容限屬性,另一個定位和left:50%

http://jsfiddle.net/NvaEE/

<br> 
<div class="first"> I have a fixe dwidth</div> 
<br> 
<div class="second"> I have a fixe dwidth</div> 

div{width:200px; background:#ddd;} 

div.first{margin:0 auto;} 
div.second{position:absolute;left:50%;margin-left:-100px} 
1

可以居中不跨越整個頁面的任何股利。說你的div是

.div { 
width: 80%; 
margin: 0 auto; 
} 

然後它會正常工作。正如埃文所說的「顯示:內聯塊;」將使div與其內容一樣寬,這也將以「margin:0 auto」起作用。

0

你敷在跨越頁面寬度的div容器,並給該容器div的,

text-align: center; 

的CSS屬性。

還有其他方法,例如管理邊距和寬度。對於大多數情況下,你可以通過文本對齊來獲得。