0

我想将 a<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。请帮助

4

1 回答 1

4

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

┏━━━━━━━━━━━━━━━━━━━━━┓
┃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 */
于 2012-07-22T17:14:34.837 回答