我很难理解一些非常基本的 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>
现在我不明白两件事:
- 为什么这两个 float 元素(div.regular 和 p)与 float 的 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”的行框。那些线盒被制作成围绕 float 回流。由 p 本身生成的 block 盒(它又包含那些线盒)按照第一句中的描述进行布局,仅仅是因为 block 盒遵循与线盒不同的布局规则。
- >
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:
- the background and borders of the element forming the stacking context.
- the child stacking contexts with negative stack levels (most negative first).
- the in-flow, non-inline-level, non-positioned descendants.
- the non-positioned floats.
- the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
- the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
- 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/