html – 基本的CSS浮动元素行为

我很难理解一些非常基本的CSS浮动规则.

假设我有一个像这样的HTML结构:

* {
    padding: 0;
    margin: 0;
}
div {
    width: 200px;
    height: 100px;
}
.base {
    float: left;
    border: 10px solid green;
}
.regular {
    height: 50px;
    border: 10px solid blue;
}
p {
    border: 10px solid red;
}
<div class="base"></div>
<div class="regular"></div>
<p>Some text</p>

现在我不明白两件事:

>为什么这两个浮动元素(div.regular和p)与浮动div.base元素的左边缘对齐?我希望它们将与右边缘对齐,因此它们将位于基本div元素的旁边.
>为什么div.base元素高于所有其他元素?我希望它在底部,因为它在HTML流程中就在它们之前.

如果你对我有所了解或给我一些资源来理解它,我将不胜感激.

最佳答案 您可以参考CSS2.1规范的第9节来回答您的两个问题.

>

Why are those two floating elements (div.regular and p) aligned to the left edge of the floated div.base element? I would expect they will be aligned to the right edge so they will be next to the base div element.

section 9.5开始:

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.

行框指的​​是实际包含文本的框.在您的示例中,p元素包含一个或多个带有“Some text”字样的行框.这些线盒用于在浮子周围回流.由p本身生成的块框(其又包含那些行框)按照第一句中的描述进行布局,这仅仅是因为块框遵循与行框不同的布局规则.
>

Why is the div.base element above all other elements? I would expect it at the bottom since it is before them in the HTML flow.

section 9.9开始,强调我的:

Within each stacking context, the following layers are painted in back-to-front order:

  1. the background and borders of the element forming the stacking context.
  2. the child stacking contexts with negative stack levels (most negative first).
  3. the in-flow, non-inline-level, non-positioned descendants.
  4. the non-positioned floats.
  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  7. the child stacking contexts with positive stack levels (least positive first).

项目#3指的是div.regular和p,因为它们处于正常流程中,它们是块级的,并且它们是未定位的. #4指的是div.base,它是浮动的.

元素按源顺序绘制时

>您有多个属于同一类别的元素,例如,当您有两个浮动元素时,或
>此列表中未提及.

点赞