清除浮动的几种方式
2018-01-23 10:28
169 查看
效果图如下:
清除浮动前:
清除浮动后:
以下方式中,浮动元素的父元素均没有设置宽高
第一种方式:给浮动的元素的父元素加上overflow属性
第二种方式:增加额外标签
第三种方式:使用伪类元素来清除浮动
清除浮动前:
清除浮动后:
以下方式中,浮动元素的父元素均没有设置宽高
第一种方式:给浮动的元素的父元素加上overflow属性
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .container{ width: 100px; height: 100px; margin: 15px; background: #ccc } .item{ width: 50px; height: 50px; float: left; margin: 10px; background: #666; } .test{ overflow: hidden; } </style> </head> <body> <div class="test"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="container"></div> <div class="container"></div> <div class="container"></div> <script> // 因为overflow: hidden会触发BFC。BFC的意思是,我这个元素里面的子孙元素,不会影响外部元素的布局(从BFC的本意来说,必须给浮动元素撑出高度)。overflow:hidden首先会计算height: auto;的真实高度,由于其触发了BFC,需要包含子元素,所以高度不是0,而是子元素高度。这时overflow:hidden;才起到隐藏作用,不过父元素高度足够大,所以子元素没有被隐藏。 // 形成 BFC 的条件 // 1、浮动元素,float 除 none 以外的值; // 2、绝对定位元素,position(absolute,fixed); // 3、display 为以下其中之一的值 inline-blocks,table-cells,table-captions; // 4、overflow 除了 visible 以外的值(hidden,auto,scroll) </script> </body> </html>
第二种方式:增加额外标签
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .container{ width: 100px; height: 100px; margin: 15px; background: #ccc } .item{ width: 50px; height: 50px; float: left; margin: 10px; background: #666; } .clear{ clear: both } </style> </head> <body> <div class="test"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="clear"></div> </div> <div class="container"></div> <div class="container"></div> <div class="container"></div> <script> // 如上。在浮动元素之下再放一个标签,加上clear: both,就可以清除浮动 </script> </body> </html>
第三种方式:使用伪类元素来清除浮动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .container{ width: 100px; height: 100px; margin: 15px; background: #ccc } .item{ width: 50px; height: 50px; float: left; margin: 10px; background: #666; } .test:after{ /*设置内容为空*/ content: ""; /*高度为0*/ height: 0; /*行高为0*/ line-height: 0; /*将文本转为块级元素*/ display: block; /*将元素隐藏*/ visibility: hidden; /*清除浮动*/ clear: both; } .test{ /*为了兼容IE*/ zoom: 1 } </style> </head> <body> <div class="test"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="container"></div> <div class="container"></div> <div class="container"></div> <script> // 给浮动元素的父元素加上伪类,样式如上所写,就可以清除浮动 </script> </body> </html>
相关文章推荐
- 清除浮动的几种方式
- 清除浮动的几种方式,各自的优缺点
- css考核点整理(一)-浮动的理解和清除浮动的几种方式
- 【css】清除浮动的几种方式
- 清除浮动的几种方式
- 【html/css】清除浮动的几种方式
- 清除浮动的几种方式
- 清除浮动的几种方式
- 清除浮动的几种方式
- 清除浮动的几种方式
- 清除浮动的几种方式
- 清除浮动的几种方式--css基础
- 清除浮动的几种方式
- 清除浮动的几种方式
- CSS 清除浮动的几种方式
- css清除浮动的几种方式
- 清除浮动常用的几种方式
- 清除浮动的几种方式总结
- 2016/2/24 1,css有几种引入方式 2,div除了可以声明id来控制,还可以声明什么控制? 3,如何让2个div,并排显示。4,清除浮动 clear:left / right / both
- 清除浮动的几种方式