【问题标题】:CSS clear both inside childrenCSS clear both inside children
【发布时间】:2012-06-28 23:12:31
【问题描述】:

我在这个问题上困扰了很长时间。我相信浮动布局是一个很常见的问题,我希望有人能给出一个“标准”的解决方案。

作为标题,问题在于嵌套浮动。考虑以下简单布局:

<div class='parent clearfix'>
     <div id='child1' style='float:left; width:500px'>
         { ... child 1 content goes here ... }
     </div>
     <div id='child2' style='margin-left:501px;'>
         { ... child 2 content goes here ... }
     </div>
</div>

这里 clearfix 是自动清除浮动子项的常用技术。问题是,如果 child2 包含另一个 clearfix 元素,布局就会被破坏。例如,如果孩子 2 的内容是:

<div class='inside clearfix'>
    <div class='sub1' style='float-left; width:100px'> 
        { ... extra content goes here ... } 
    </div>
    <div class='sub2' style='margin-left:101px'> 
        { ... extra content goes here ... } 
    </div>
</div>

所以一般来说,如果我们使用 clear:both inside 浮动布局(在非浮动元素内部),它也会清除父容器。

如果使用绝对位置和一点js,我知道该怎么做,但这不是一个好习惯。

如何使用 float 修复它?

谢谢!

【问题讨论】:

    标签: css css-float


    【解决方案1】:

    你也可以使用溢出:隐藏;

    <div class="wrapper">
      <div class="float"></div>
      <div class="float"></div>
    </div>
    
    .wrapper{
     overflow: hidden;
    }
    
    .float{float: left;}
    

    jsfiddle查看演示

    【讨论】:

    • 溢出:隐藏是CSS中最神秘的东西!我想 clear:both 是多余的。
    【解决方案2】:

    在使用浮点数时,我采用了一种更简单的方法,即使用带有类 clear 的额外 div。这更容易、易于理解且不易出错。

    以下是我的工作:

    <div class="parentClass">
        <div class="float1">
        . . .  
        </div>
        <div class="float2">
        . . .
        </div>
        <div class="clear"></div>
    </div>
    

    在 CSS 中,clear 类如下所示:

    .clear { clear:both; overflow:hidden; }
    

    您可以尝试这种方法,我相信事情会顺利进行。祝你好运!

    【讨论】:

    • 这个方法没有给出完整的100%宽度(加上float1和float2),需要用到JS。此外,如果您必须在 float2 元素中再次使用 floatclear:both ,则会破坏布局。这是我想问的问题。
    猜你喜欢
    • 2012-10-04
    • 2011-05-11
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    相关资源
    最近更新 更多