css - 如何使用:after to clear floats

标签 css

为什么 :after 的使用不能成功清除 float ,以便内容出现在新行上?

Fiddle

HTML:

<div id="left-block"></div>
<div id="right-block"></div>
<div>Content</div>

CSS:

#left-block {float:left; border:1px solid red; width:200px; height:200px;}
#right-block {float:left; border:1px solid green; width:200px; height:200px;}
#right-block:after {clear:both; content:""; display:block;}

截图:

enter image description here

最佳答案

按如下方式更改您的 html:

<div id="clearfix">
    <div id="left-block"></div>
    <div id="right-block"></div>
</div>
<div>Content</div>


你的 css 是:

#left-block {
    float:left;
    border:1px solid red;
    width:200px;
    height:200px;
}
#right-block {
    float:left;
    border:1px solid green;
    width:200px;
    height:200px;
}
#clearfix:after {
    clear:both;
    content:"";
    display: table;
}


基本上,您需要为 float div 提供父级,并为 :after 伪类提供 table 的显示。
这是因为您需要清除 float div 的父级而不是子级本身

DEMO

关于css - 如何使用:after to clear floats,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22857729/

相关文章:

html - 删除标签生成的文本

html - CSS 不适用于 HTML 文件

html - dontent div min-height=100% 创建空白

php - 根据多数组中的键计算 Rowspans 和 Colspans 的数量

html - 关于在使用某些第 3 方 css 框架时如何在网页中显示用户输入的 html 的任何想法

html - 悬停时强制结束 CSS 过渡

html - 如何让我的文字对齐我的图片?

javascript - 如何仅使用 CSS 在悬停另一个元素时显示 div

javascript - jQuery 选择选项跳过选项组键盘箭头

php - echo php定位