CSS清除浮动float的三种方法小结

Hadara ·
更新时间:2024-09-20
· 587 次阅读

一、浮动的定义

使元素脱离文档流,按照指定方向发生移动,遇到父级边界或者相邻的浮动元素停了下来。

ps:文档流:文档流是文档中可显示对象在排列时所占用的位置 。

语法

float常跟属性值left、right、none

float:none 不使用浮动

float:left 靠左浮动

float:right 靠右浮动

二、浮动的用途

可设置文字环绕或使元素宽度由内容填充(类似Inline-block)。使用浮动需要注意的是如果浮动的元素高度比父级容器还高,那么需要设置父级容器的overflow属性为auto,使其自动撑满。

三、浮动用法

分析HTML结构:

<div class="box"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> </div>

分析CSS代码样式:

.box { border: 1px solid #ccc; background: #fc9; color: #fff; margin: 50px auto; padding: 50px; } .div1 { width: 100px; height: 100px; background: darkblue; float: left; } .div2 { width: 100px; height: 100px; background: darkgoldenrod; float: left; } .div3 { width: 100px; height: 100px; background: darkgreen; float: left; }

 

清除浮动

方法一:添加新元素,应用clear:both;

HTML:

<div class="box"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> <div class="clear"></div> </div>

CSS:

.clear { clear: both; height: 0; line-height: 0; font-size: 0 }

 

一切恢复作用啦。

方法二:父级div定义overflow:auto;

HTML:

<div class="box"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> </div>

CSS:

.box { border: 1px solid #ccc; background: #fc9; color: #fff; margin: 50px auto; padding: 50px; overflow: auto; zoom: 1; /*zoom: 1; 是在处理兼容性问题 */ }

结果:也是实现了。

方法三:在父级样式添加伪元素:after或者:before(推荐)

HTML:

<div class="box"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> </div>

CSS:

.box { border: 1px solid #ccc; background: #fc9; color: #fff; margin: 50px auto; padding: 50px; } .box:after{ content: ''; display: block; clear: both; }

结果:当然不用说啦

 

总结

以上所述是小编给大家介绍的CSS清除浮动float的三种方法小结,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对软件开发网网站的支持!



小结 float 方法 CSS

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章