我有这个简单的 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 正好位于黄色上方并将其隐藏:
但是当黄色方 block float 时:
#black {
background-color: black;
}
#yellow {
background-color: yellow;
float:left;
}
我们得到:
我想弄清楚这背后的逻辑。 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/