css - 为什么这个 block div 会影响两个 float div?

标签 css css-float margin

假设我有三个<div>在我的页面中:

<div id="left" class="test" style="float:left;"></div>
<div id="right" class="test" style="float:right;"></div>
<div id="footer">footer</div>

使用这个CSS:

.test{  background:black;height:200px;width:200px;}
#footer{    background:yellow;margin:20px 0 0 0;}

我想要的是:

  • 让“#left”向左浮动
  • 让“#right”向右浮动
  • 不对“#footer”进行任何更改,只需将其设置为 margin: 20px;

结果如下:

enter image description here

但我想知道为什么 float 的 div 也有与 #footer 相同的边距。 。它们是 float 的,因此它们独立于其他元素,为什么 #footer 会这样?会影响他们吗?

最佳答案

以及页脚上的clear:both,只需在元素周围添加一个容器“包装器”div 即可阻止这种情况发生 - example

实际上在页脚上添加 clear: Both; 也不会给您的 float 和页脚之间提供 20px 的间隙,您实际上需要向 float 添加 20px 的底部边距 -原因都与clearance or non clearance有关。它与Collapsing Margins的交互

为什么?

您说您想知道为什么会发生这种情况,在您的 OP 场景中,这是因为边距崩溃

原始示例中没有涉及间隙,因此 float 被删除,因此页脚边距仍然相邻,因此与 body 元素折叠,因此 body 元素是获得边距的元素,然后因为 float 实际上仍然在 body 内部,所以它们也获得了边距。

正如我上面提到的,创建一个包装器 div 来“包含” float 会阻止这种情况发生,因为折叠规则也是如此。但是,您选择包含 float ,或者使用 overflow:hidden ,或者通过 float “包装器”来停止此交互,因为..来自折叠边距部分:

Vertical margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.

你会看到, float 和“可见之外的溢出”这两个属性都是“包含 float 子项”的方法 - 实际上它们正在建立一个新的 block 格式化上下文,但简单地说,大多数人都知道它是“包含” float ”;)

现在一旦你有了这个,就修复了你的第一个位,但是如果你决定在页脚上引入 clear:both ,现代浏览器将不会放置 20px float 和页脚之间的边距..这实际上是正确的..来自 clear 属性的部分(我的粗体):

Then the amount of clearance is set to the greater of:

  1. The amount necessary to place the border edge of the block even with the bottom outer edge of the lowest float that is to be cleared.

  2. The amount necessary to place the top border edge of the block at its hypothetical position.

为了将页脚的上边缘放置在 float 下方(在您的示例中),浏览器必须引入 200 像素的间隙,这远远超过 20 像素,因此它遵循规则 1。如果页脚的上边距为 220 像素,该边距将大于所需的任何间隙,因此它将遵循规则 2。

因此,如果您确实希望页脚位于 float 元素下方 20 像素,无论 float 元素的高度是多少,您都可以将 20 像素作为底部边距放在两个 float 元素上,这样它[页脚]就会通过间隙清除规则1, float 具有所需的间隙/边距,无论哪个 float 最长。

PS:不要在 IE7 或更低版本中测试以上内容 - 我希望它不会太无聊;)

关于css - 为什么这个 block div 会影响两个 float div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5609531/

相关文章:

css - 如何添加填充/边距以移动 :after up

css - 检测内联/ float 元素被推到新行

html - 这个 margin 是从哪里来的?

css - 使搜索框响应

html - 位置固定重叠问题?

jquery - addClass() 可以工作,但它有一个 css 优先级问题

javascript - 如何缩放背景图像并使其与浏览器大小一起使用

css - Firefox 4.0 CSS 改变了吗? float 问题?

javascript - 在无序列表中定位元素

css - 为什么我的网页顶部有空隙?