1,BFC
参考文档:
1,如何触发BFC
- overflow: hidden
- display: inline-block
- position: absolute
- position: fixed
- display: table-cell
- display: flex
2, BFC规则
- BFC是一个块级元素,块级元素会在垂直方向一个接一个的排列。
- BFC是页面中的一个隔离的独立容器,容器中的标签不会影响到外部标签。
- 属于同一个BFC的两个相邻标签的外边距会发生重叠。
- 计算BFC的高度时,浮动元素也参与计算。
3,BFC解决的问题
- 使用float脱离文档流,容器高度塌陷
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>高度塌陷</title>
<style>
.box {
margin: 100px;
width: 100px;
height: 100px;
background: red;
float: left;
}
.container {
background: #000;
/* display: inline-block; */
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
<div class="box"></div>
</div>
</body>
</html>
块级格式化前:
块级格式化后:
2,水平垂直居中
1.利用绝对定位
<style>
.father {
width: 300px;
height: 150px;
background-color: #385185;
position: relative;
}
.son {
/* 子元素采用绝对定位*/
position: absolute;
/* 控制子元素与包含块各边的距离 */
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 200px;
height: 100px;
background-color: #cd0000;
/* 内边距自动计算 */
margin: auto;
}
</style>
<div class="father">
<div class="son"></div>
</div>