Why does a nested HTML element make my CSS jump?

与世无争的帅哥 提交于 2019-12-12 11:56:58

问题


Here's a puzzle. Basic page, one element:

http://jsfiddle.net/PZj6t/

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;
}
​

That one looks how I want, with the #container neatly flush to the top. But when I add a nested element:

http://jsfiddle.net/PZj6t/1/

HTML:

<div id="container">
    <nav id="topnav"></nav>
</div>​

CSS (new):

#topnav {
    width: 100%;
    height: 40px;
    margin: 30px 0;
    background-color: red;
}
​

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?

(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.)


回答1:


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.

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/

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).




回答2:


display:inline-block;

On Your nav element appears will fix this. Its to do with margin-collapsing see here for more detail.




回答3:


Jblasco is correct, this is a neater solution though: http://jsfiddle.net/PZj6t/4/

#container {
    position: relative;
    margin: -1px auto 0;
    width: 400px;
    height: 100%;
    padding-top:1px;
    background-color: #666;
}
#topnav {
    width: 100%;
    height: 40px;
    margin: 29px 0 30px;
    background-color: red;
}



回答4:


#container {
    margin: 0 auto;
    width: 400px;
    height: 100%;
    background-color: #666;
    border:1px solid;
}

http://jsfiddle.net/PZj6t/12/

Update:

http://jsfiddle.net/PZj6t/1/
apply display:inline-block; on both container and topnav



来源:https://stackoverflow.com/questions/9519024/why-does-a-nested-html-element-make-my-css-jump

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!