为什么.clearfix类不适用于浮动元素?

时间:2015-10-14 20:34:23

标签: html css floating clearfix

在这个帖子中:What is a clearfix?

我看到最好的答案说 clearfix可以直接添加到最后一个浮动元素

  

使用clearfix,您只需要

编写HTML代码:

<div class="clearfix">
    <div style="float: left;" class="clearfix">Sidebar</div>
</div>

和CSS代码:

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

但是,当我尝试将clearfix添加到浮动元素时,它根本不起作用(如下面的代码段所示):

&#13;
&#13;
.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

div#container {
    background-color: green;
    width: 50%;
    display: block;
    margin: auto;
}
.floating {
    float: left;
    margin: 1px;
    background-color: yellow;
}
&#13;
<div id="container">
    <div class='floating'>1</div>
    <div class='floating clearfix'>2</div>

</div>
&#13;
&#13;
&#13;

从结果中可以看出,#container的高度仍为0。似乎clearfix不起作用,不能直接添加到最后一个浮动元素。这是真的吗?有没有人有这方面的想法?

2 个答案:

答案 0 :(得分:4)

您已使用clearfix上的container

&#13;
&#13;
.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

div#container {
    background-color: green;
    width: 50%;
    display: block;
    margin: auto;
}
.floating {
    float: left;
    margin: 1px;
    background-color: yellow;
}
&#13;
<div id="container" class="clearfix">
    <div class='floating'>1</div>
    <div class='floating'>2</div>

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

您需要添加:after元素,该元素应该清除容器末尾的子元素,而不是浮动元素本身。您所要做的就是为容器提供类clearfix,如下所示:

<div id="container" class="clearfix">
    <div class="floating">1</div>
    <div class="floating">2</div>
</div>