css - div 在另一个中间

标签 css html margin

我想放置一个 <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;
}

如您所见,填充和边距无法将其置于页面中间(这意味着 whiteboxredbox 的顶部和底部之间有相同的位置。 请帮忙

最佳答案

好吧,让我们看看你有什么。此图中的每条线代表 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/

相关文章:

jquery - 父级到子级悬停

javascript - 即使屏幕分辨率发生变化,我如何让我的图像在页面上移动

javascript - 如何让div一次显示一个,设置为一个时间

html - 使用显示 :flex 时文本溢出不起作用

whitespace - Bxslider 不需要的顶部和底部空白

html - Tumblr 在帖子中添加不需要的填充?

css - 我如何判断哪种样式覆盖了另一种样式?

css 背景图像被截断

css - 旧样式信息在 getStylesheets().clear() 之后出现

html - 有效和无效的 HTML 标签