gpt4 book ai didi

html - float :left and display:block contradiction

转载 作者:行者123 更新时间:2023-11-28 17:30:30 26 4
gpt4 key购买 nike

导航栏使用 float:left 并排排列列表项。但是,使用 float 不是意味着使用 display:block 吗?因此,既然 block 元素是垂直堆叠的,为什么 float:left 会将它们并排放置?另外,from W3C :

In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats (although a box's line boxes may shrink due to the floats), unless the box establishes a new block formatting context (in which case the box itself may become narrower due to the floats).

(强调我的)

这不是说每个元素如果是一个 block 无论如何都应该垂直堆叠?

最佳答案

稍后在规范中您有 section on floats ,您可以在哪里找到:

"A floated box is shifted to the left or right until its outer edge touches the containing block edge or the outer edge of another float. If there is a line box, the outer top of the floated box is aligned with the top of the current line box.

If there is not enough horizontal room for the float, it is shifted downward until either it fits or there are no more floats present.

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."

请注意“因为 float 不在流中”,这意味着 float 不会在 block 格式上下文中作为 block 布局。 float 按照自己的规则布局,不会影响流中的 block 元素(但会影响 block 内的文本流)。

如果 float 元素后跟一个非 float 元素, float 元素将被放置在左侧或右侧,然后非 float 元素将作为 block 放置,就好像 float 元素不存在一样。

两个元素向左和向右浮动,后面跟着一个非 float 元素:

<div class="a"></div>
<div class="b"></div>
<div class="c">text</div>

CSS:

.a { float: left; background: red; width: 50px; height: 50px; }
.b { float: right; background: green; width: 50px; height: 50px; }
.c { background: yellow; height: 100px; }

float 元素最终会出现在非 float 元素之上,但其中的文本会围绕 float 元素流动:

+------+--------------------------------------+------+
| |text | |
| | | |
| | | |
+------+ +------+
| |
| |
| |
+----------------------------------------------------+

演示:http://jsfiddle.net/Guffa/kmbuw53v/

关于html - float :left and display:block contradiction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26208899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com