如何在标记中不使用<div class ="clear">

Tom*_*Tom 18 css xhtml clear

我的代码总是充满了<div>用于清除/扩展div以使其正确的代码.每当它看起来不正确时,我添加一个<div style="clear:both;">,它解决了IE7中的问题.

我该如何避免这样做?我搞砸了overflow:auto,overflow:hidden我一无所获.

提前致谢

Nic*_*ole 35

一种常见的方法是clearfix班级.<div style="clear:both;">您不必在浮动元素之后需要无关元素(就像您一直在做的那样),只需将此类添加到浮动元素本身,然后布局就会自动清除.1

我最喜欢的是来自http://perishablepress.com/press/2009/12/06/new-clearfix-hack.它支持现代浏览器以及IE6和IE7.

/* new clearfix */
.clearfix:after {
    visibility: hidden;
    display: block;
    font-size: 0;
    content: " ";
    clear: both;
    height: 0;
    }
* html .clearfix             { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */
Run Code Online (Sandbox Code Playgroud)

示例(旧/坏):

<div class="floatingrightmenu">This floats right</div>
<div style="clear:both;"></div>
<p>This text is cleared below it.</p>
Run Code Online (Sandbox Code Playgroud)

示例(新增clearfix):

<div class="floatingrightmenu clearfix">This floats right</div>
<p>This text is cleared below it.</p>
Run Code Online (Sandbox Code Playgroud)

1:注意:自动清除意味着它对单浮动元素最有效.如果您希望将多个元素彼此相邻浮动,请将它们全部放入一个也浮动的容器中并应用于clearfix该容器.

  • @Kristian - 我没有这样解释问题.我解释说他希望避免"代码充满了`<div>`s",换句话说,必须将`<div style ="clear:both;">`**放在*浮动元素之后.这是确切的解决方案. (2认同)