DIV+CSS 清除浮动是页面布局中常见的问题,相信各位高手也都有自己的方法,今天在这里对常见的几种方法进行总结(PS:谈不上是原创,这里是我自己做的归纳总结,也是我自己内化的过程),希望对您能够有所帮助。
DIV+CSS 浮动效果是指,父元素在未定义高的情况下,由于子元素全部浮动脱离文本流,而造成父元素高的塌陷(PS:正常情况下,父元素的高是由子元素撑起来);或者因为部分子元素的而浮动,脱离文本流而造成其他元素的布局错乱的情况。
DIV+CSS 清除浮动 常见的方法如下:
1、给未加浮动的子元素的CSS添加 clear: both;若子元素都有浮动时,可以新增加一个空的子元素,并且给其的CSS添加 clear: both;这样可以利用清除左右浮动的子元素重新撑起父元素的高,从而达到清除浮动的效果。代码及效果如下:
CSS Code复制内容到剪贴板
- <style type="text/css">
- .fl{float:left;}
- .demo{background:#ccc;}
- .item1{background:#F571E3;height:100px;width:100px;}
- .item2{background:#21B2F7;height:200px;width:100px;clear: both;}
- </style>
- </head>
- <body>
- <h2>用 clearfix 清除浮动</h2>
- <div class="demo">
- <div class="fl item1"></div>
- <div class="item2"></div>
- </div>
- </body>
清除浮动前,item1左浮动的效果(此时父元素的高是被未浮动的item2元素的高撑开):

清除浮动前,item1右浮动的效果(此时父元素的高是被未浮动的item2元素的高撑开):

清除浮动后的效果(因为DIV是块级元素,会独占一行,所以item2会在下面一行,此时父元素的高是被item1元素和item2元素的高撑开):

2、子元素全部浮动时,给父元素的CSS添加 overflow: hidden;(子元素没有全部浮动时,不浮动的元素会撑开父元素的高,但是由于浮动元素造成的布局应该再利用padding进行修改),但是此方法父元素不能改使用position进行定位,否则不起作用。代码及效果如下:
CSS Code复制内容到剪贴板
- <style type="text/css">
- .fl{float:left;}
- .demo{background:#ccc;overflow: hidden;}
- .item1{background:#F571E3;height:100px;width:100px;}
- .item2{background:#21B2F7;height:200px;width:100px;}
- </style>
- </head>
- <body>
- <div class="demo">
- <div class="fl item1"></div>
- <div class="fl item2"></div>
- </div>
- </body>
清除浮动前的效果,由于父元素的高塌陷,所以背景 background:#ccc; 没有起效果:

清除浮动后的效果:

3、给父元素加 伪类:after 和 zoom,代码及效果如下:
CSS Code复制内容到剪贴板
- <style type="text/css">
- .fl{float:left;}
- .demo{background:#ccc;zoom: 1;}
- .demo:after{display:block;clear:both;content:"";visibility:hidden;height:0}
- .item1{background:#F571E3;height:100px;width:100px;}
- .item2{background:#21B2F7;height:200px;width:100px;}
- </style>
- </head>
- <body>
- <div class="demo">
- <div class="fl item1"></div>
- <div class="fl item2"></div>
- </div>
- </body>
清除浮动前的效果,由于父元素的高塌陷,所以背景 background:#ccc; 没有起效果:

清除浮动后的效果:

4、如果是在使用bootstrapt,则可以给其父元素添加class 为 clearfix 的类,代码及效果如下:
CSS Code复制内容到剪贴板
- <style type="text/css">
- .fl{float:left;}
- .demo{background:#ccc;}
- .item1{background:#F571E3;height:100px;width:100px;}
- .item2{background:#21B2F7;height:200px;width:100px;}
- </style>
- </head>
- <body>
- <div class="demo clearfix">
- <div class="fl item1"></div>
- <div class="fl item2"></div>
- </div>
- </body>
清除浮动后的效果:

以上方法各有利弊,大家可以根据自己的理解选择使用,还有一些其他的清除浮动的方法,例如让父元素浮动、让父元素 display:table 等等其他,个人并不推荐使用。
以上这篇DIV+CSS 清除浮动常用方法总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
原文地址:http://www.cnblogs.com/Lily-nercel/archive/2016/05/06/5465592.html