更新:在2014年,您应该使用一种利用伪元素的clearfix技术,例如@RodrigoManguinho提到的方法。这是清除浮动的现代方法。要获取更加新的方法,请参考Nicholas Gallagher的Micro clearfix:
/**
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* contenteditable attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that are clearfixed.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.cf:before,
.cf:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.cf:after {
clear: both;
}
/**
* For IE 6/7 only
* Include this rule to trigger hasLayout and contain floats.
*/
.cf {
*zoom: 1;
}
翻译后的答案:
我不喜欢使用额外的非语义标记,因此避免使用清除元素。相反,只需将 overflow: hidden;
应用于浮动元素的父级即可清除它们。跨浏览器都有效,没有问题。我相信 overflow: auto;
也可以。
显然,如果您想使用不同的 overflow 属性,这种方法将无法奏效,但由于 IE6 扩展框错误,我很少有理由故意使容器溢出。
我发现大多数情况下(包括我自己),这种方法在HTML中使用:
<div class="clear"></div>
有了这个样式表:
.clear {clear: both;}
.clear
的样式永远不会改变,那么 class="clear"
怎么比 style="clear:both"
好呢?仅仅增加一层间接性并不能真正等同于更好的设计。 - tylerlstyle
属性的争论。 - Geoff.clear-fix:after
{
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.clear-fix
{
zoom: 1;
}
<div class="clear-fix">
<div class="left">Some Div With Float</div>
<div class="left">Another Div With Float</div>
</div>
在我看来,这是最好的方法。不需要额外的DOM元素或错误使用溢出或任何黑客技巧。
我发现自己经常使用一些神秘的技巧。
<span class="clear"></span>
span.clear {
display: block;
clear: both;
width: 1px;
height: 0.001%;
font-size: 0px;
line-height: 0px;
}
这种组合神奇地解决了许多浏览器问题,我已经使用它很长时间,忘记了它解决了什么问题。
<p>
和类似情况下使用它时,它非常有用,因为不能使用<div>
。 - its_mediv.container {overflow: auto;}
在大多数情况下,只需将overflow:auto;
添加到包含浮动元素的父元素中即可解决问题。
示例 HTML:
<div class="container">
<div class="child">...</div>
<div class="another-child">...</div>
<div>
CSS:
.child {
float: right;
word-wrap: break-word;
}
.child img {
max-width: 100%;
height: auto; /* of course, this is default */
}
.child p {
word-wrap: break-word;
}
.container {
overflow: auto;
}
overflow:auto;
也有一些需要注意的地方。为了解决这些问题,对于图像应用max-width:100%; height: auto;
,对于浮动元素中包含的文本应用word-wrap: break-word;
。jQuery UI有一些类可以解决这个问题(ui-help-clearfix
执行某些操作)。
从技术上讲,<div style="clear:both;"></div>
比<br style="clear:both;" />
更好,因为一个空的div将具有0高度,从而清除浮动。 <br />
会留下一个空格。使用<div/>
方法没有问题。
display: flow-root
来代替clearfix hack作为父元素。.box {
display: flow-root;
}
display: flow-root
。float
以强制它适应其浮动子元素的高度,然后将您的css clear
应用于您实际想要清除的下一个元素。通常需要添加width:100%
,因为如果不浮动父级,则可能会意外更改布局。<br>
或带有clearfix类的<div>
。.floatWrapper {
overflow:hidden;
width:100%;
height:100%;
}
.floatLeft {
float:left;
}
<div class="floatWrapper">
<div class="floatLeft">
Hello World!
</div>
<div class="floatLeft">
Whazzzup!
</div>
</div>
overflow:auto
是最好的解决方案) - Šime Vidas