将孩子置于父母内部 [英] Centering a child inside it's parent
问题描述
我正在将#child设为#parent,高度和宽度均为100%。为什么将#child顶部位置设置为10%工作,但使用10%作为边距顶部不会?
I'm working to center #child within #parent at 100% height and width. Why does setting the #child top position to 10% work, but using 10% as a margin-top does not?
http://jsfiddle.net/rbtstudio/SCmfG/
<style>
html {
height: 100%;
}
body {
height: 100%;
overflow: hidden;
}
#parent {
width: 100%;
height: 100%;
background-color: #323232;
}
#child {
width: 80%;
height: 80%;
background-color: #eaeaea;
margin: 0 auto;
position: relative;
top: 10%;
}
/*
#child {
width: 80%;
height: 80%;
margin-top: 10%;
margin-right: auto;
margin-bottom: 0;
margin-left: auto;
}
*/
</style>
<div id="parent">
<div id="child"></div>
</div>
推荐答案
这里的问题被称为折叠边距。您可以在css规格中阅读更多相关资讯。
The issue here is called "collapsing margins". You can read more about them in the css spec.
http://www.w3.org/TR/CSS21/box.html#collapsing-margins
而不是保证金不工作,这是保证金正在崩溃,导致保证金应用于父框的顶部。
It's not that the margin isn't working, it's that the margin is collapsing, causing the margin to apply to the top of the parent box.
您会注意到,
一种解决方法(许多)避免边缘折叠是添加 overflow:hidden
到父元素:
One workaround (of many) to avoid the collapsing of margins is to add overflow: hidden
to the parent element:
编辑:另一个重要点要记住(这是在另一个答案已被删除)是所有百分比边距是基于元素的宽度,即使是顶部和底部的百分比。
Another important point to keep in mind (which was in another answer which has since been deleted) is that all percentage margins are based on a percentage of the width of the element, even top and bottom.
这篇关于将孩子置于父母内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!