为什么 .clearfix class 不适用于浮动元素?
Why does .clearfix class not work on floating element?
在此线程中:What is a clearfix?
我看到最佳答案说clearfix可以直接添加到最后一个浮动元素:
With clearfix, you only need to
编写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
添加到浮动元素时,它根本不起作用(如下面的代码片段所示):
.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;
}
<div id="container">
<div class='floating'>1</div>
<div class='floating clearfix'>2</div>
</div>
从结果中可以看出,#container
的高度仍然是0
。 clearfix好像不行,不能直接加到最后一个浮动元素上。是真的吗?有人对此有想法吗?
您需要添加 :after
元素来清除容器末尾的子项,而不是在浮动元素本身内。您所要做的就是给容器 class clearfix
,像这样:
<div id="container" class="clearfix">
<div class="floating">1</div>
<div class="floating">2</div>
</div>
您必须在 container
上使用 clearfix
。
.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;
}
<div id="container" class="clearfix">
<div class='floating'>1</div>
<div class='floating'>2</div>
</div>
在此线程中:What is a clearfix?
我看到最佳答案说clearfix可以直接添加到最后一个浮动元素:
With clearfix, you only need to
编写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
添加到浮动元素时,它根本不起作用(如下面的代码片段所示):
.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;
}
<div id="container">
<div class='floating'>1</div>
<div class='floating clearfix'>2</div>
</div>
从结果中可以看出,#container
的高度仍然是0
。 clearfix好像不行,不能直接加到最后一个浮动元素上。是真的吗?有人对此有想法吗?
您需要添加 :after
元素来清除容器末尾的子项,而不是在浮动元素本身内。您所要做的就是给容器 class clearfix
,像这样:
<div id="container" class="clearfix">
<div class="floating">1</div>
<div class="floating">2</div>
</div>
您必须在 container
上使用 clearfix
。
.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;
}
<div id="container" class="clearfix">
<div class='floating'>1</div>
<div class='floating'>2</div>
</div>