清除浮動
css使用了浮動 導致了父元素的塌陷問題 要是用清除浮動
父盒子塌陷了
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
background: red;
}
.box1 {
float: left;
width: 200px;
height: 200px;
background-color: blue;
}
.box2 {
float: right;
width: 400px;
height: 100px;
background: cyan;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>
1 .clear清楚浮動
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
background: red;
}
.box1 {
float: left;
width: 200px;
height: 200px;
background-color: blue;
}
.box2 {
float: right;
width: 400px;
height: 100px;
background: cyan;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
<div style="clear: both;"></div>
</div>
</body>
</html>
2 . overflow: hidden
給父盒子添加 overflow: hidden
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
margin: 60px;
width: 900px;
background: red;
overflow: hidden;
}
.box1 {
float: left;
width: 200px;
height: 200px;
background-color: blue;
}
.box2 {
float: right;
width: 400px;
height: 100px;
background: cyan;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>
3 僞類 (常用)
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
margin: 60px;
width: 900px;
background: red;
*zoom: 1;
}
.container::after {
content: "";
display: block;
/* 不能少 */
visibility: hidden;
/* 元素是不可見的。 */
clear: both;
overflow:hidden;
}
.box1 {
float: left;
width: 200px;
height: 200px;
background-color: blue;
}
.box2 {
float: right;
width: 400px;
height: 100px;
background: cyan;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>
BFC
1. 定義
BFC(Block formatting context)直譯爲"塊級格式化上下文"。它決定了元素如何對其內容進行定位以及與其他元素的關係和相互作用當涉及到可視化佈局的時候Block Formatting Context提供了一個環境HTML元素在這個環境中按照一定規則進行佈局
是 Web 頁面的可視化 CSS 渲染的一部分,是塊盒子的佈局過程發生的區域,也是浮動元素與其他元素交互的區域。
2. 作用
形成一個完全獨立的空間,讓空間中的子元素不會影響到外面的佈局
- 利用BFC避免margin重疊。解決margin塌陷、margin合併、清除浮動流
- 左邊定寬右邊自適應兩欄佈局
- 子元素設置爲浮動時,出現父元素盒子坍塌的問題
3. 觸發方式
- float不爲none (left right)
- position不爲relative和static (absolute fixed)
- overflow爲auto scroll和hidden
- display的值爲table-cell或inline-bloc