浮動的定義:
元素脫離文檔流
舉栗子:
//HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="home">
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
</div>
</body>
</html>
//CSS
.home{
border:1 px solid;
margin:50px auto;
padding:50px;
background: red;
}
.left{
height:80px;
width:80px;
background:blue;
float:left;
}
.right{
height:80px;
width:80px;
background:yellow;
float:left;
}
.center{
height:80px;
width:80px;
background:green;
float:left;
}
1.png
修改 CSS 代碼,清除浮動:
.home{
border:1 px solid;
margin:50px auto;
padding:50px;
background: red;
}
.left{
height:80px;
width:80px;
background:blue;
}
.right{
height:80px;
width:80px;
background:yellow;
}
.center{
height:80px;
width:80px;
background:green;
}
1.png
浮動的影響:
父元素高度塌陷
清除浮動:
1.在浮動的子元素后面添加一個空的 div 設置屬性 clear :both(在左右兩側均不允許浮動元素)或者可以試著添加空行 br 效果等同于div 設置 clear:both;
//HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="home">
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
<div class='test'></div>
//<br clear="both">
</div>
</body>
</html>
//添加CSS
.test{
clear:both;
}
1.png
2.給父元素設置寬和高,但是如果父元素寬和高不確定這個方法就不適用
//修改 CSS
.home{
border:1 px solid;
margin:50px auto;
padding:50px;
background: red;
width:500px;
height:100px
}
1.png
3.給父元素設置浮動,但是如果可能會引起新的問題,而且需要給每個父元素都設置浮動。
//修改 CSS
.home{
border:1 px solid;
margin:50px auto;
padding:50px;
background: red;
float:left
}
1.png
4.給父級添加 overflow:hidden 清浮動方法
//修改 CSS
.home{
border:1 px solid;
margin:50px auto;
padding:50px;
background: red;
overflow:hidden
}
1.png
5.偽類清除浮動,在父容器的尾部自動創建一個子元素
//添加 CSS
:after{
content:".";
clear:both;
display:block;
height:0;
overflow:hidden;
visibility:hidden;
}
1.png