html - float :left and display:block contradiction

标签 html css css-float

导航栏使用 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/

相关文章:

javascript - 如果元素有类什么都不做运行匿名函数

html - 如何让两列 float 左 div 布局自动换行?

html - div 旁边的垂直对齐标题

html - &lt;header&gt; 文本覆盖 <figure>

css - 如果 CSS 为 "user-select=none"的元素文本位于元素之间,则会被复制

css - 使用固定位置将我的导航保持在顶部

css - 读取 : Center nested DIVs

jquery - 无法在 div 内 float 跨度

html - 在订阅按钮旁边对齐社交图标

javascript - 尝试将 HTML 文件转换为包含套接字 io 的 JavaScript 时出现语法错误,SyntaxError : Unexpected token <