html - 元素排序对 CSS 中 float 的影响

标签 html css layout web css-float

我有这个简单的 HTML:

<body>          
    <div class="square" id="black"></div>
    <div class="square" id="yellow"></div>           
</body>

这是 CSS:

.square {
    height: 50px;
    width: 50px;    
}

#black {
    background-color: black;            
    float:left;   
}

#yellow {
    background-color: yellow;          
}

据我所知,当一个元素 float 时,它就脱离了页面流。就好像 float 元素和非 float 元素相互忽略一样。所以黑色方 block 正好位于黄色上方并将其隐藏:

enter image description here

但是当黄色方 block float 时:

#black {
    background-color: black;                      
}

#yellow {
    background-color: yellow; 
    float:left;          
}

我们得到:

enter image description here

我想弄清楚这背后的逻辑。 html 中的元素排序 float 机制 如何一起发挥作用?谁在何时获胜?

最佳答案

W3C Float Spec实际上很好地回答了这个问题。

A float is a box that is shifted to the left or right on the current line... 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.

这解释了为什么在第一个示例中 float 覆盖了黄色框。

对于第二个例子,#black 在内容流中,是display: block,因此有自己的一行。 #yellow 在这种情况下位于不同的行上。

关于html - 元素排序对 CSS 中 float 的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14866819/

相关文章:

具有动态列数的 CSS3 列布局

html - 为子元素制作背景剪辑

javascript - *ngFor 在获取新数据之前正在更新

javascript - 切换溢出 - jQuery

html - 围绕一个点居中文本

java - Java GUI 不能看起来像我想要的那样吗...?

android - 如何在运行时设置按钮的属性 "android:drawableTop"

html - 为什么表格会在左右两侧添加额外的空间?

html - 在我的网站 html 上使用 2 个样式表

css - 再次单击时如何关闭 Accordion 菜单