html - 基本 CSS float 元素行为

标签 html css css-float

我很难理解一些非常基本的 css float 规则。

假设我有一个这样的 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>

现在我不明白两件事:

  1. 为什么这两个 float 元素(div.regular 和 p)与 float 的 div.base 元素的左边缘对齐?我希望它们与右边缘对齐,因此它们将紧挨着基础 div 元素。
  2. 为什么 div.base 元素位于所有其他元素之上?我希望它位于底部,因为它在 HTML 流中位于它们之前。

如果你能为我阐明这一点或给我一些资源来理解它,我将不胜感激。

最佳答案

您的两个问题都可以通过引用 CSS2.1 规范的第 9 节来回答。

  1. >

    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”的行框。那些线盒被制作成围绕 float 回流。由 p 本身生成的 block 盒(它又包含那些线盒)按照第一句中的描述进行布局,仅仅是因为 block 盒遵循与线盒不同的布局规则。

  2. >

    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,因为它们在正常流中,所以它们是 block 级的,并且它们是非定位的。 #4 指的是 div.base,它是 float 的。

    元素按源顺序绘制

    • 您有多个属于同一类别的元素,例如当您有两个 float 元素时,或者
    • 此列表中未提及的其他内容。

关于html - 基本 CSS float 元素行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33868412/

相关文章:

jquery - 有没有等同于 jQuery.offset 的 Elm?

javascript - 固定 100% 高度侧边栏,滚动后粘在页脚上

asp.net - 水平并排设置两个 <divs>

CSS float 砌体

java - HTML 到 Textile Java 库

javascript - js脚本一直执行onchange

css - joomla 错误的 base href 导致错误的 CSS 模板

css - float div 不会将其他 div 推到正确的位置

javascript - Google Chart - 调暗除鼠标悬停的系列之外的所有其他系列

HTML 电子邮件中的 CSS