简体   繁体   English

CSS:清除浮动div内的内容有什么用?

[英]CSS: What does clearing INSIDE a floated div do?

Quick question! 快速提问! Does putting a "clear" element INSIDE a floated div do anything? 将“ clear”元素放在浮动div内是否有作用? Like: 喜欢:

<div style="float: right">
blah blah
<div style="clear: right"></div>
</div>

Somewhere somehow I got the impression that this helps the div expand to contain the content inside of it. 我以某种方式得到的印象是,这有助于div扩展以包含其中的内容。 What does it actually do? 它实际上是做什么的? Anything? 有什么事吗 Thanks! 谢谢!

An element which contains nothing but floats will collapse in height, because the floated elements are no longer in the normal document flow. 仅包含浮点数的元素的高度会折叠,因为浮点的元素不再位于常规文档流中。 In such a case, clearing after the floats will allow the containing element to retain its height. 在这种情况下, 浮子进行清理将使容纳元件保持其高度。

<div id="container">
    <div id="float1" style="float:left;"></div>
    <div id="float2" style="float:right;"></div>
    <!-- if you use a clearing element, it should go here -->
</div>

Note that there are other ways to clear than using clearing elements, such as adding overflow:hidden; 注意,除了使用清除元素外,还有其他清除方法,例如添加overflow:hidden; to the container styles. 容器样式。

In your example, since the div with clear: right is nested, it doesn't clear anything. 在您的示例中,由于带有clear:right的div是嵌套的,因此它不会清除任何内容。 Float applies to elements at the same level. 浮点数适用于相同级别的元素。 If the divs were at the same level, the second div would appear below the div that has float: right. 如果div处于同一级别,则第二个div将出现在具有float:right的div下方。 This page has some good explanations/examples of how float works: float tutorial 此页面对float的工作方式有一些很好的解释/示例: float教程

In your case, not much effect. 就您而言,效果不大。 the enclosed div (clear: right) is as good as redundant. 封闭的div(清除:正确)和冗余一样好。

<div style="float: right; background: red;" >
blah blah
<div style="clear: right; background: blue;"></div>
</div>

With this, you can visually see if you enclosed div made a difference. 这样,您可以直观地看到封闭的div是否有所作为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM