我有一个两列布局,其中一个向左浮动,另一个不是:
<div id="left">
LEFT
</div>
<div id="right">
RIGHT
</div>
CSS 是:
#left {
float: left;
width: 200px;
background: yellow;
}
#right {
margin-left: 200px;
background: orange;
}
在没有 float 的 right
元素中,我有这样的标记:
<div id="nav">
<div class="item">LINK</div>
<div class="item">LINK</div>
<div class="item">LINK</div>
<div class="item">LINK</div>
<div class="item">LINK</div>
<div class="clear"></div>
</div>
<h1>Welcome World</h1>
nav
和 item
的 CSS 是(如您所见,item
是 float 的):
#nav {
background: blue;
}
.item {
background: green;
float: left;
margin-right: 10px;
}
我的 clear
元素是:
.clear {
clear: both;
}
最后,我得到了这个结果:
我认为问题出在我的 clear
元素上,它也在clearing float 元素 (#left
)。
但我希望得到这个结果:
最佳答案
无需在 HTML 中添加不需要的标记,您只需添加 overflow: hidden;
至 #nav
.这将为 #nav
中的列表项创建一个新的 block 格式化上下文。 , 因为 float 元素从 normal flow 中取出(它的流入容器不会尊重它们的高度,请注意我的 fiddle 中的 <body>
没有向下延伸到 #left
)
来自Visual Formatting Model, 9.4.1:
Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
#nav {
background: blue;
overflow: hidden; /* Creates a new block-formatting context
for floated descendants */
}
关于html - 非 float 元素上的 float 元素 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16889698/