浮動的定義:
當元素設置了浮動屬性,元素的寬度會隨着內容的變化而變化,其次,會對緊鄰在其後的元素造成影響,使元素脫離了文檔流,按指定方向上移動,遇到父級邊界或者相鄰的浮動元素就停下來。
1、加寬父級元素
給父級元素設定一個大於子元素的width值,使之可以完全包裹子層。
2、給父級加浮動(margin左右失效)
.fatherbox{
border: 5px solid red;
float: left;
}
.son1{
width: 300px;
height:300px;
background-color: blue;
float: left;
}
3、用inline-block(margin左右auto失效)
.fatherbox{
border: 5px solid red;
display: inline-block;
}
.son1{
width: 300px;
height:300px;
background-color: blue;
float: left;
}
4、空標籤(定義一個空內容的標籤,在其裏面設置clear:both)
.fatherbox{
border: 5px solid red;
float: left;
}
.son1{
width: 300px;
height:300px;
background-color: blue;
float: left;
}
/*這是空標籤*/
.div1{
clear: both;
}
5、br清浮動(br裏有個屬性clear:all)(但不符合結構、樣式、行爲三者分離)
<div class="fatherbox">
<div class="son1">我是子層</div>
<!-- 這個br要放在後面,放在前面就會造成換行效果 -->
<br clear="all"/>
</div>
6、after僞類(主流方法)
<head>
<title>清除浮動的測試</title>
<style type="text/css">
.fatherbox{
border: 5px solid red;
}
.clearfix:after{
content: "";
display: block;
clear: both;
}
.son1{
width: 300px;
height:300px;
background-color: blue;
float: left;
}
</style>
</head>
<body>
<div class="fatherbox clearfix">
<div class="son1">我是子層</div>
</div>
</body>
6、overflow:hidden;