我已经习惯了通过使用来清理我的花车,<br style="clear:both"/>但是东西一直在变化,我不确定这是不是最好的做法.
有一个CSS hack(来自positioneverything)可以让你在没有清除div的情况下实现相同的结果.但是......他们声称黑客有点过时了,相反你也许应该看看这个黑客.但是...阅读了700页的评论后:)似乎可能有一些地方后者黑客不起作用.
我想避免任何javascript hacks因为我希望我的清除工作,无论启用javascript.
以浏览器独立方式清除div的当前最佳实践是什么?
Bry*_* M. 57
更新: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;
}
Run Code Online (Sandbox Code Playgroud)
原答案:
我真的不喜欢使用额外的非语义标记,所以我远离使用清除元素.而不是仅仅应用于overflow: hidden;浮点数的父级来清除它们.跨浏览器工作,没问题.我相信overflow: auto;也有效.
显然,如果你想使用不同的溢出属性它将无法工作,但由于IE6扩展盒错误,我很少有理由故意溢出我的容器.
查看有关使用的更多信息,overflow而不是clear避免添加额外的标记.
Mik*_*ike 27
我发现最常见的(包括我自己),这个方法用在html中:
<div class="clear"></div>
Run Code Online (Sandbox Code Playgroud)
在样式表中使用:
.clear {clear: both;}
Run Code Online (Sandbox Code Playgroud)
Rod*_*nho 23
.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>
Run Code Online (Sandbox Code Playgroud)
在我看来,这是最好的方式.无需额外的DOM元素或错误使用溢出或任何黑客攻击.
有一点伏都教,我倾向于发现自己正在使用.
<span class="clear"></span>
Run Code Online (Sandbox Code Playgroud)
span.clear {
display: block;
clear: both;
width: 1px;
height: 0.001%;
font-size: 0px;
line-height: 0px;
}
Run Code Online (Sandbox Code Playgroud)
这种组合神奇地修复了一大堆浏览器问题,我刚刚使用它已经忘记了它解决了什么问题.