CSS Absolute Positioning of one div being affected

2019-07-04 15:52发布

问题:

Given the following I would expect a 200px red box at the top of the page followed by a white space of 100 pixels then a purple box on the bottom. This is what the WYSIWYG view in Dreamwever shows me but what I get in FF IE Chr is a red box in the middle of the page. Funny thing is if I add a border to the wrapper div I get what I expect.

So what is happening is that the margin-top:300px of the #content div is pushing down the #header div. Since the #header div is positioned absolutely inside of the #wrapper div i dont get why this is happening.

<style>
#wrapper{
    width:960px;
    margin:0 auto;
    background-color:#fff;
    position:relative;
    border:0px solid green;
    }
#header{
    width:960px;
    height:200px;
    background-color:#f00;
    position:absolute;
    top:0px;
    left:0px
    }
#content{
    width:960px;
    background-color:#f2f;
    margin-top:300px;
    }
</style>


<div id="wrapper">
    <div id="header">header</div>
    <div id="content">content<br  /><br  /><br  /></div>
</div>

回答1:

Yes, you are on the right track. What is really happening is the 300px margin is being applied to #wrapper (and thus, pushing down #header along with it) because of the W3C box-model behavior of collapsing margins.

In this case, the "top margin of a box and top margin of its first in-flow child" are collapsed: #wrapper's 0px top-margin and #content's 300px top-margin are combined into a single top-margin for #wrapper (#content is first in-flow child since #header has an absolute position).

A simple way to fix this, besides a border or change #header's position, is simply to change the margin to a padding:

#content{
  width:960px;
  background-color:#f2f;
  padding-top:300px;
}

See http://www.w3.org/TR/CSS2/box.html#collapsing-margins