一个div的CSS绝对位置受无关div的边距影响 [英] CSS Absolute Positioning of one div being affected by margin in unrelated div

查看:91
本文介绍了一个div的CSS绝对位置受无关div的边距影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下原因,我希望页面顶部有一个200px的红色框,然后是100像素的空白,然后是底部的紫色框.这就是Dreamwever中所见即所得的视图向我显示的内容,但是我在FF IE Chr中看到的是页面中间的一个红色框.有趣的是,如果在包装div上添加边框,我会得到期望的结果.

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.

因此,发生的是#content div的margin-top:300px向下推#header div.由于#header div绝对位于#wrapper div的内部,所以我不明白为什么会这样.

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>

推荐答案

是的,您的做法正确.实际发生的事情是将300px的空白应用于 #wrapper (因此,将#header与其一起向下推),因为合拢边距.

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.

在这种情况下,框的顶部边距和第一个流入子项的顶部边距"被折叠: #wrapper 的0px顶部边距和 #content 的300px上边距被合并为 #wrapper 的单个上边距(#content是第一个流入的子级,因为#header具有绝对位置).

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

解决此问题的一种简单方法,除了边框或更改#header的位置外,只需将边距更改为填充:

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

请参见 http://www.w3 .org/TR/CSS2/box.html#collapsing-margins

这篇关于一个div的CSS绝对位置受无关div的边距影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆