2010-01-14 160 views
1

我試圖在另一個div內居中設置一個div。居中在另一個div內的div

這是HTML頁面:

<body> 
<div id="divParent"> 
    <div id="divHeader" > 
     <div id="divHeaderText"> 
     </div> 
    </div> 
    <div id="divBody"> 
    </div> 
</div> 
</body> 

而這種風格:

#divHeader { 
    background-color: #C7C7C7; 
    font-family: Verdana, Geneva, Tahoma, sans-serif; 
    height: 80px; 
    margin-bottom: 2px; 
} 
#divBody { 
    background-image: url('images/GradientBackground.png'); 
    background-repeat: repeat-x; 
    height: 300px; 
} 
#divHeaderText { 
    margin: auto; 
    width: 90%; 
    height: 80%; 
    background-color: #00FF00; 
} 

爲什麼最小的DIV不會留在它的頂部空間?

+0

你到底在問什麼? – SLaks 2010-01-14 18:14:10

+0

我在垂直詢問中心。 – VansFannel 2010-01-14 20:09:46

回答

3

你的問題不清楚。

如果您嘗試將#divHeaderText垂直居中於#divHeader之內,請嘗試添加margin-top: 13px;

0

對於水平居中,可以使用文本對齊:在內聯元素或邊距上居中:0在容器和塊級元素上設置寬度。

對於文本的垂直居中,可以將line-height屬性設置爲等於包含div的高度。

要水平居中div,您可以應用margin-top屬性將它隔開到中心。

請注意,設計問題更適合於http://www.doctype.com/,因爲SO主要面向服務器端語言和應用程序編程。

2

margin:auto不適用於垂直對齊。您必須在px,em等中給出確切的數字。在您的示例中,這不應該成爲問題,因爲您知道父容器的高度。

0
#divHeaderText { 
margin: auto; 
width: 90%; 
height: 64px; /* 80% of 80px */ 
margin-top: 8px; /* (80 - 64)/2 = 8 */ 
background-color: #00FF00; 
} 
+0

你試過了嗎?我正在使用Internet Explorer 8和Firefox 3.5.7,並且此解決方案不起作用。我使用的是螢火蟲,我發現divHeaderText不在divHeader中。 – VansFannel 2010-01-15 16:22:00