CSS properties being passed up to the parent eleme

2019-02-28 06:28发布

问题:

This problem is happening for me on IE8 and Chrome which makes me think this is a standards thing.

I am creating a site with header and menu using DIVs that do not have any content but do have background images and heights / widths set in CSS. I want the inner DIV to have margin against the parent div but it applies the margin to the parent div. Putting content within the divs corrects this. IE7 does not have this problem. I do not want to use   because it does throw things out and it seems like a hack.

Please see example code to recreate below:

<style>

#header{
    width:600px;
    height:300px;
    background-color:red;
}

#headerMenu{
    height:100px;
    width:500px;
    margin-left:auto;
    margin-right:auto;
    background-color:blue;
    margin-top:20px;
}

</style>

<div id="header">
    <div id="headerMenu">
    </div>
</div>

If you give the parent div content or even a border the layout works correctly. I've hit this same problem a few times on this site. I wanted to give a margin-top to a list of menu items but as the headerMenu div (its parent) also does not have any content it bubbles up the property.

What's going on?

回答1:

I think you're running in to margin collapsing.

See the CSS 2.1 spec on margin collapsing for more info.



回答2:

Yes, it's a standards thing. It's called margin collapsing, and the reason that you don't see it in IE7 is most likely because IE7 gets it wrong.

Margins are a bit tricky as they don't specify an area around an element, but rather the minimum distance between elements. Margin collapsing happens when a child element has a margin and the parent element doesn't have padding or borders. The margin is applied between the child element and the surrounding elements, not between the child element and the parent element.

As some browsers (only IE that I know of) doesn't handle collapsing margins correctly, you should avoid them for now. Use padding instead if possible, or set a padding or a border on the parent to avoid the margins to collapse.



回答3:

Try adding overflow: auto to the #header css code.

For example,

#header{
    width:600px;
    height:300px;
    background-color:red;
    overflow: auto;
}

EDIT: Seems like position: absolute works as well.



回答4:

I just had this problem as well and added this to the css

border: 0px solid;


标签: css html margin