1、CSS浮動產生原因
一般是一個盒子里使用了CSS float浮動屬性,導致父級對象盒子不能被撐開,這樣CSS float浮動就產生了。
2、CSS浮動影響
1、背景不能顯示
??由于浮動產生,如果對父級設置了(CSS background背景)CSS背景顏色或CSS背景圖片,而父級不能被撐開,所以導致CSS背景不能顯示。
2、邊框不能撐開
??如上圖中,如果父級設置了CSS邊框屬性(css border),由于子級里使用了float屬性,產生浮動,父級不能被撐開,導致邊框不能隨內容而被撐開。
3、margin padding設置值不能正確顯示
??由于浮動導致父級子級之間設置了css padding、css margin屬性的值不能正確表達。特別是上下邊的padding和margin不能正確顯示。
3、清除浮動影響的方法
(1)使用clear屬性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>浮動高度塌陷</title>
<style type="text/css">
*{
margin:0px;
padding: 0px;
}
.left{
width: 100px;
height: 100px;
background: red;
float: left;
}
.right{
width: 100px;
height: 100px;
background: blue;
float: right;
}
.wrap{
background: gray;
border: 1px solid yellow;
width: 500px;
margin:20px auto;
}
</style>
</head>
<body>
<div class="wrap">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
</html>
運行效果:
清楚浮動前
使用clear:both 清楚浮動
<div class="wrap">
<div class="left"></div>
<div class="right"></div>
<div style="clear: both"></div>
</div>
運行效果:
清楚浮動后
(2)使父元素BFC
??給父wrap元素添加 overflow:hidden屬性,使其產生BFC。運行效果與clear:both 效果相同。