在使用css布局页面的时候往往会使用float布局元素,这时有可能会出现因为浮动,父元素出现高度为0的情况,如图所示
这时会根据项目需要对浮动的元素进行清除,以避免父元素出现为高度0的情况。常见的方法如下:
第一种 、<div class="clearboth"></div>
在子元素里面多加一个div(或者其他带有clear:both样式的元素)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#od>div{float:left;height:100px;width:100px;margin:0 10px;background:#ccc;}
.clearboth{clear:both;height:0;}
</style>
</head>
<body>
<div class="ob" id="od">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="clearboth"></div>
</div>
</body>
</html>
第二种、伪类::after清除方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#od>div{float:left;height:100px;width:100px;margin:0 10px;background:#ccc;}
#od::after{content:"";display:block;clear:both;}
</style>
</head>
<body>
<div class="ob" id="od">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</body>
</html>
第三种、使用overflow属性进行清除
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#od>div{float:left;height:100px;width:100px;margin:0 10px;background:#ccc;}
#od{overflow:auto;}/***设置hidden也可以**/
</style>
</head>
<body>
<div class="ob" id="od">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</body>
</html>
第一种则会在项目中多加了一个无用的dom元素,一般情况出现的少,第二种使用css伪类在一些比较低版本的浏览器中可能会出现兼容性问题,第三种使用overflow属性也有存在的弊端,比如如果如长度超出了会出现隐藏等现象,所以一般在项目中使用第二种居多,可以兼容大部分用户浏览器。