首页 > 开发 > CSS > 正文

CSS 清除浮动元素方法 整理

2024-07-11 08:45:21
字体:
来源:转载
供稿:网友
例如:
<div style=”background:#666;”>
<div style=”float:left; width:30%; height:40px;background:#EEE; “>Some Content</div>
</div>
  此时预览此代码,我们会发现最外层的父元素float container,并没有显示。这是因为子元素因进行了浮动,而脱离了文档流,导致父元素的height为零。
  若将代码修改为:

<div style=”background:#666;”>
<div style=”float:left; width:30%; height:40px;background:#EEE; “>Some Content</div>
<div style=”clear:both”></div>
</div>
  注意,多了一段清理浮动的代码。这是一种好的CSS代码习惯,但是这种方法增加了无用的元素。这里有一种更好的方法,将HTML代码修改为:

<div class=”clearfix” style=”background:#666;”>
<div style=”float:left; width:30%; height:40px;background:#EEE; “>Some Content</div>
</div>
定义CSS类,进行“浮动清理”的控制:

复制代码
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表