为什么 float-right 元素没有一直到顶部?

Why does the float-right element not go all the way to the top?

我知道会发生这种情况,但想澄清原因,因为我正试图更好地理解浮动机制

鉴于此 HTML

<div class="wrapper">
  <div class="inner first">1</div>
  <div class="inner second">2</div>
  <div class="inner third">3</div>
</div>

还有这个CSS

.wrapper {
  width: 500px;
  height: 500px;
  margin: 100px auto;
  border: 1px solid black;
}

.inner {
  border: 1px solid black;
  box-sizing: border-box;
}

.first, .second {
  float: left;
  width: 300px;
  height: 300px;
}

.third {
  width: 200px;
  height: 200px;
  float: right;
}

第三个div并没有一直浮动到右上角,而是与第二个div

对齐

我知道会发生这种情况,但我想更具体地解释为什么(基于什么规则)

好问题,我看到有些人很难理解这个问题。根据您的问题,我觉得您想将“3”对齐到框中的右上角。你的里面是500 * 500,你的第一个和第二个是300 * 300,因为它不能容纳总共600个,第二个会在第一个下面。然后是第三个 space 200。它将需要下一个 200 space(紧接着第二个)并且不使用上面的 space。要获得所需的输出,您需要如下所示向上移动 3,以便首先使用右上角 200 的 space。

也许这对你有帮助:

  <div class="wrapper">
  <div class="inner third alg">3</div>
  <div class="inner first">1</div>
  <div class="inner second ">2</div>
  </div>

CSS代码:

.wrapper {
  width: 500px;
  height: 500px;
  margin: 100px auto;
  border: 1px solid black;
}

.inner {
  border: 1px solid black;
  box-sizing: border-box;
}

.first, .second {
  float: left;
  width: 300px;
  height: 300px;
}

.alg{
  text-align: right;
}

.third {
  width: 200px;
  height: 200px;
  float: right;
}

我希望这能让您现在更加清楚。如果不在下面评论,我可以用更多的例子来解释。

那是因为 float rules

  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.

由于[=10=右边的space不够,所以.second放在下面。但是 .third 不能放在 .second 上面,即使它适合 .first.

留下的可用 space

这是因为页面流顺序。当您浮动一个元素时,您并没有将它完全从页面的流动顺序中移除,而是指定它应该将自己定位在元素的左侧或右侧。通过将 div 向右浮动三个,您并没有像绝对定位 div 那样将其完全从流中移除。

在你的例子中div一和二的净宽度比父包装宽。这意味着他们不能内联休息,所以他们堆叠。 Div 在其之前的元素右侧的三个位置(div 二)但仍受流顺序的影响并位于 div 一之下。