2012-07-22 35 views
0

我想将<div>放置到另一个中,并希望居中。 我的方法是这样的:div在另一个中间

<div id="redthing"> 
<div id="whitebox" > 
</div> 
</div> 

名为.css - 代码如下:

#redthing { 
margin-top: 2px; 
background-color: #f00d28; 
height: 250px; 
} 

#whitebox { 
margin: 0 auto; 
margin-top: 10px; 
padding-top: 20px; 
height: 10px; 
width: 400px; 
background-color: white; 
border:5px solid #000; 
} 

就像你所看到的,空白和边距不工作,使其中心在页面的中间(这意味着存在whitebox和顶部和redbox的底部之间的同一个地方。 请帮

+0

见http://stackoverflow.com/questions/396145/whats-the-best- way-of-centering-a-div-vertical-with-css – 2012-07-22 17:10:00

回答

4

好吧,让我们来看看你有什么。在此图中的每一行代表HEIG 10px的ht:

┏━━━━━━━━━━━━━━━━━━━━━┓ 
┃10px margin top  ┃ 
┃┌─────────────────────┐┃ 
┃│20px padding top  │┃ 
┃│padding continues │┃ 
┃│10px height   │┃ 
┃└─────────────────────┘┃ 
┃      ┃ 
┊ lots of empty space ┊ 
┃      ┃ 
┗━━━━━━━━━━━━━━━━━━━━━┛ 

解释这应该如何工作?

要么你需要确保你的填充和保证金加起来正确的金额,或使用本:

/* add this to the container */ 
position: relative; 

/* add this to the inner box */ 
position: absolute; 
top: 50%; 
margin-top: -Xpx; 
/* where X is half the offsetHeight of the box - ie. (height+padding+border)/2 */ 
+0

你打败了我! – cereallarceny 2012-07-22 17:15:32

+0

@Fresheyeball请不要编辑我的答案,如果你只是想打开盒子图纸。 – 2012-07-22 19:14:35

+0

@Kolink对不起,我认为线路的损坏是错误的。我的错。 – Fresheyeball 2012-07-22 20:52:50