css-float - 为什么左边距会跳起来?

标签 css-float margin css

我正在关注In Search of the Holy Grail ,但我无法理解第 3 步中实际发生的情况。

为了解决这个问题,我禁用了“左”和“右”div 的边距/偏移。这会为您提供顶部的内容,然后是并排位于其下方的其他两个元素,正如我所期望的[参见 P1]

然后,我逐渐将“左”div 的左边距从 0px 减小到 -199px,这再次达到了我的预期[参见 P2]

但在 -200px(左侧元素本身的宽度)时,它会上升到顶部[参见 P3],左边缘紧靠内容的右边缘。我本以为它会继续超出边缘。

为什么会跳起来?如果没有概念性解释为什么,那么它在规范中的哪里描述了该功能?

图片:

P1

Photo 1


P2

Photo 2


P3

Photo 3

最佳答案

请记住,#content#left(以及 #right)都是 float 的。

由于 float 的性质,它们(或其内容)可能会重叠。 this section of the spec对此进行了很好的描述。 ,并且相当容易理解。如果您将负边距应用于与另一个 float 元素相邻的 float 元素,则该元素将简单地移动到其左侧(类似于具有相对偏移量),其同级元素。

float property 部分,您将找到“控制 float 行为的精确规则”的列表。现在,我并不是 100% 熟悉 float 模型,但我认为以下几点是相关的:

2. If the current box is left-floating, and there are any left-floating boxes generated by elements earlier in the source document, then for each such earlier box, either the left outer edge of the current box must be to the right of the right outer edge of the earlier box, or its top must be lower than the bottom of the earlier box. Analogous rules hold for right-floating boxes.1

7. A left-floating box that has another left-floating box to its left may not have its right outer edge to the right of its containing block's right edge. (Loosely: a left float may not stick out at the right edge, unless it is already as far to the left as possible.) An analogous rule holds for right-floating elements.

8. A floating box must be placed as high as possible.

9. A left-floating box must be put as far to the left as possible, a right-floating box as far to the right as possible. A higher position is preferred over one that is further to the left/right.

所以我的猜测是:-200px 的边距,正如你所说,相当于 #left 元素本身宽度的负值,导致它一直向上 float 并向右(而不是向左)并拥抱 #center 元素的边缘,该元素本身也是 float 的。由于这个完整、相等的负边距,两个元素的右边缘相互接触。因此,当您继续增加(或减少?)负边距时,您会看到 #left 元素继续向左侧移动。

请注意,应用于 #container 元素的内边距不会与边距交互;即使您删除一侧或两侧的内边距,边距也会以相同的方式交互。


1 另请注意,collapsing margins 部分中有一个声明。在规范的链接部分中,它描述了负边距的行为,但这无关紧要,因为我们在这里关心的边距是水平的并且属于 float 元素,因此永远不会受到折叠的影响。

关于css-float - 为什么左边距会跳起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10787470/

相关文章:

css - 如何创建包含的 css 列。可滚动的中间列和 float 的左右列

html - 水平子菜单

css - Firefox 和 Chrome 上的 margin-top

Safari 中的 CSS 全宽背景图像(负边距)

css - 如何在SASS、SCSS中实现直接父选择器?

html - 渲染 float 元素有时会将它们推到导航栏下方

css - 是否可以在 bootstrap V4 strip 表中的每一行之间添加边距

css - 用于在 Sublime Text 2 中显示所有可能的 CSS 值的包?

html - 如何为某些绝对位置 div 设置背景颜色?

html - IE的单页对齐