html – 非浮动元素上的浮动元素:

我有一个两列布局,其中一个向左浮动,另一个不是:

<div id="left">
    LEFT
</div>

<div id="right">
    RIGHT
</div>

CSS是:

#left {
    float: left;
    width: 200px;
    background: yellow;
}

#right {
    margin-left: 200px;
    background: orange;
}

在没有浮动的正确元素中,我有一个这样的标记:

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

导航和项目的CSS是(如你所见,项目是浮动的):

#nav {
    background: blue;
}

.item {
    background: green;
    float: left;
    margin-right: 10px;
}

而我的明确要素是:

.clear {
    clear: both;
}

最后,我得到了这个结果:

我认为问题在于我的清晰元素也在清除浮动元素(#left).
但我希望得到这个结果:

Here is the fiddle demo

最佳答案 您可以添加overflow:hidden;而不是在HTML中添加不需要的标记.到#nav.这将为#nav中的列表项创建一个新的块格式化上下文,因为浮动元素从
normal flow中取出(其流入容器不会尊重它们的高度,请注意< body>不向下扩展到#left in my fiddle)

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 */
}

http://jsfiddle.net/bJFUj/9/

点赞