CSS 浮动逻辑

CSS Float Logic

我创建了25个随机宽高的盒子,其中width == height(如图)

$(document).ready(function(e) {
  for (var count = 0; count < 5; count++) {
    for (var iter = 0; iter < 5; iter++) {
      $(".content").append("<div id='" + count + "_" + iter + "' class='box'><p>" + count + "_" + iter + "</p></div>");
      $(".content div:last").width(Math.round((Math.random() * 100) + 50));
      $(".content div:last").height($(".content div:last").width());
    }
  }
});
.box {
  background: #FF0004;
  margin: 10px;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="content">
  </div>
</body>

我试图更好地理解浮动 属性 逻辑以及浮动元素相互“堆叠”时定位背后的原因。例如(截图来自 fiddle):

是什么让3_3在屏幕变大的时候会重新定位到如下图的位置?

根据 W3Schools:

If you place several floating elements after each other, they will float next to each other if there is room.

所以问题是,“room”是什么意思,控制浮动元素位置的逻辑是什么?

这个 SO post 的答案:CSS Float explanation 似乎是相关的,但它似乎没有解释为什么浮动元素会停在某个位置。

这是链接答案中与您的问题最相关的部分:

When you float a block element, you are telling the browser to position it next to the previous floated object, so long as the container is wide enough (otherwise it will drop below the previous object).

正如作者所提到的,这是一种粗略的简化。规范的 Section 9.5.1 列出了所有精确的规则,但我不打算在这里引用全部内容,因为它是 非常 的长读物并且只有某些要点在这里是相关的。当我逐步了解您的 fiddle.

中发生的事情时,我将引用相关要点

比较你的两张截图。注意位置发生变化的两个框3_2和3_3,以及它们周围的框2_4、3_0和3_1。

之前

之后

当屏幕变大时,您为 3_2 腾出空间,从它在 2_4 旁边的原始位置向上移动并在 3_1 旁边:

  1. 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.
  1. A floating box must be placed as high as possible.
  1. 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.

这又为下一个浮动框腾出空间,以尽可能向上和向左占据 space,遵循与上述相同的规则。结果,3_3 向上浮动,停在 3_2 附近, 然后 它沿水平轴尽可能向左浮动,停在附近2_4。请注意,即使看起来 3_3 应该能够适合 2_4 和 3_2 之间,但事实并非如此,因为必须考虑边距(这就是 [= 的意思) 51=] 以上)。

此时,以下项目适用,除了上面的 项#8 和#9:

  1. 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. The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.

由于 3_3 太大,因此第一行浮动框明显向下突出。这有效地增加了第一行的高度。 3_3 之后的所有其他浮动元素必须保留在自己的行中,并且第二行浮动元素不得与 3_3 的底部边距边缘相交。这主要由项目 #5 管理。