我想放置一个 <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
的顶部和底部之间有相同的位置。
请帮忙
最佳答案
好吧,让我们看看你有什么。此图中的每条线代表 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 */
关于css - div 在另一个中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11602244/