没有给父元素设置固定的高度,那么父元素的高度由子元素撑开.当子元素都设置了浮动后,平面上没有元素,自然父元素的高度就为0了.
给父元素设置下列几种属性之一即可: overflow:hidden; float:left; display:inline-block; position:absolute;
当父元素形成BFC时,它就有一个虚拟的框,此时子元素的外边距不会和父元素的外边距合并;如果父元素没有BFC化,那么它在平面上的元素(即未发生浮动的元素)会与父元素发生外边距合并,设置浮动的子元素则不会发生合并; 所以除非父元素设置了BFC,否则子元素设置外边距是不会吧父元素大小撑开
使用幽灵元素设清除浮动,此时父元素的高与设置浮动的子元素中的最高高度一样高 设置方式:在父元素的最后新建一个空的块元素,然后给那个元素设置样式:clear:both;(这样子设置的方式有个缺点就是可能会发生元素混乱,比如在ul里只能放li元素,如果用此方法设置会导致布局乱套)
<style> body{ margin:0; } .father{ width:500px; margin:100px auto; background-color:brown; } .son1{ width:150px; height:150px; background-color: blue; } .son2{ width:200px; height:200px; background-color: cadetblue; } .son3{ float:left; width:250px; height:200px; background-color: rgb(154, 95, 160); } .clearfix{ clear:both; } </style> </head> <body> <div class="father"> <div class="son1"></div> <div class="son2"></div> <div class="son3"></div> <div class="clearfix"></div> </div> </body>所以使用改进版的幽灵元素(企业常用)
<style> body{ margin:0; } .father{ width:500px; margin:100px auto; background-color:brown; } .son1{ float: left; width:150px; height:150px; background-color: blue; } .son2{ float:left; width:150px; height:200px; background-color: cadetblue; } .son3{ float:left; width:200px; height:200px; background-color: rgb(154, 95, 160); } //设置幽灵元素 .clearfix::after{//使用after伪元素相当于在父元素的 // 末端增加一个after标签内容 content:"";//必不可少的 display:block; clear:both;//清除两端浮动 } </style> </head> <body> <div class="father clearfix"> <div class="son1"></div> <div class="son2"></div> <div class="son3"></div> </div> </body>效果如图所示,父元素还存在高度
