为什么嵌套的HTML元素使我的CSS跳转? [英] Why does a nested HTML element make my CSS jump?
问题描述
这里有一个谜题。基本页面,一个元素:
Here's a puzzle. Basic page, one element:
HTML:
<div id="container"></div>
CSS:
body, html {
height: 100%;
margin: 0;
padding: 0;
background-color: black;
}
#container {
position: relative;
margin: 0 auto;
width: 400px;
height: 100%;
background-color: #666;
}
这看起来像我想要的,用#container整齐地与顶部齐平。但是当我添加嵌套元素时:
That one looks how I want, with the #container neatly flush to the top. But when I add a nested element:
HTML:
<div id="container">
<nav id="topnav"></nav>
</div>
CSS(新):
#topnav {
width: 100%;
height: 40px;
margin: 30px 0;
background-color: red;
}
容器跳下。看来,从#topnav的margin-top不知何故被传递到容器,现在页面有一个滚动条我不想要。 (我在Chrome中测试。)如何防止这种情况?
The container jumps down. It seems that the margin-top from #topnav is somehow being passed to the container, and now the page has a scrollbar I don't want. (I'm testing in Chrome.) How do I prevent this?
(另一个谜题,如果我添加 border:1px solid white ;
(As a further mystery, if I add border: 1px solid white;
to the #container's CSS, the jump disappears. Which would be fine, except that also adds two pixels worth of undesirable scroll to the page.)
这是由于CSS的一个功能,称为边缘折叠。如果父元素没有填充或边框,则父元素及其子元素的边距会折叠为两者的较大值,并且基本上应用于父元素。
This is due to a feature of CSS called margin collapsing. If there is no padding or border on a parent element, the parent and its child's margins "collapse" to the greater value of the two and is essentially applied to the parent.
对于你的情况,我建议在容器中添加一个额外的内包装,并在它上面引入一些填充,以模拟你正在寻找的余量效应: http://jsfiddle.net/PZj6t/3/
For your situation, I would suggest simply adding an additional inner wrap within the container, and throwing some padding on it to simulate the margin effect you're looking for: http://jsfiddle.net/PZj6t/3/
#内部
div或以下应该按照您的期望行事,因为边距只有在父对象的边缘时才会折叠(并且没有填充或边框)。
Anything within the #inner
div or below should behave as you expect, as margins only collapse when they are at the edge of their parent (and no padding or borders are present).
这篇关于为什么嵌套的HTML元素使我的CSS跳转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!