因为浮动产生,若是对父级设置了css背景颜色或css背景图片,而父级不能被撑开,因此致使css背景不能显示。css
若是父级设置了css边框属性(css border),因为子级里使用了float属性,产生浮动,父级不能被撑开,致使边框不能随内容而被撑开。html
因为浮动致使父级子级之间设置了css padding、css margin属性的值不能正确表达。特别是上下边的padding和margin不能正确显示。api
对父级设置适合高度样式清除浮动,通常设置高度须要能肯定内容高度才能设置。盒子在网页中所占的高度为 height + padding2 + border2.测试
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin:0; padding:0; } ul,li { list-style: none;/*清除掉列表的默认样式*/ } .box ul li { width: 100px; height: 50px; float: left; background-color: orange; margin-left: 10px; } /*解决浮动带来影响的第一种方案:给浮动元素的父元素添加高度*/ .box { height: 50px; } </style> </head> <body> <div class="box"> <ul> <li>Html</li> <li>Css</li> <li>JavaScript</li> <li>Vue.js</li> </ul> </div> <div class="box2 clear"> <ul> <li>测试文字</li> <li>测试文字</li> <li>测试文字</li> <li>测试文字</li> </ul> </div> </body> </html>
显示结果为:
code
将上诉代码的style代码更改成:htm
<style> * { margin:0; padding:0; } ul,li { list-style: none;/*清除掉列表的默认样式*/ } .box ul li { width: 100px; height: 50px; float: left; background-color: orange; margin-left: 10px; } .clear { clear: both; } .box2 { margin-top: 1000px; } </style>
结果与上图同样,可是咱们会发现类.box2的外边距1000px并无在网页中显示出来,因此采用第二种方式会致使margin外边距失效.图片
对父级css选择器加overflow:hidden样式,能够清除父级内使用float产生浮动。优势是可使用不多css代码就可解决浮动产生。ip
<style> .d1 { width: 300px; height: 100px; border:1px solid #ccc; overflow: auto; } .test { border:2px solid red; /*可以解决父元素中子元素浮动以后父元素没有高度的问题,而且设置以后父元素的高度就会是最高的那个子元素的高度*/ overflow: hidden; /*height: 00px;*/ } .s1 { width: 300px; height: 700px; background-color:blue; float: left; } .s2 { width: 200px; height: 400px; background-color: orange; float: left; } </style> </head> <body> <div class="d1"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore totam est culpa non sapiente tempora consequuntur, ea alias nisi eos. Eum, neque consectetur totam tenetur ex pariatur magnam omnis at! </div>
结果显示为:ci
在两部分浮动元素之间,建一个墙,隔开两部分浮动(注意是在两个包含浮动元素的盒子中间)。墙要加clear:both属性。用墙本身自己的高度做为两个盒子之间的间隙。内墙法:将墙放在浮动元素所在的盒子里。与外墙法不一样的是,内墙法使得盒子被撑起了高度。rem
<style type="text/css"> div ul li { float:left; width: 100px; height: 50px; background-color: blue; list-style: none; } .h10 { height: 20px; } .c1 { clear: both; } </style> </head> <body> <div> <ul> <li>qqqqqqq</li> <li>aaaaaaa</li> </ul> <!--内墙法 <div class="c1 h10"></div> --> </div> <!--外墙法--> <div class="c1 h10"></div> <div> <ul> <li>qqqqqqq</li> <li>aaaaaaa</li> </ul> </div> </body>
外墙法与内墙法结果显示同样: