一、BFC的理解和应用
1.BFC的概念?
Block Format Context 块级格式化上下⽂,⼀块独⽴的渲染区域,内部元素的渲染不会影响边界以外的元素。
形成BFC的常⻅条件:
- float的值不等于 none;
- position值是 absolute或 fixed;
- overflow不是 visible,( overflow:hidden);
- display的值为 inline-block、table-cell;
- body根元素
如何应用?
- (BFC可以包含浮动元素)清除浮动;
- 同⼀个BFC下,垂直外边距会发⽣重叠;
二、margin外边距重叠及解决⽅法
块的上外边距(margin-top)和下外边距(margin-bottom)有时合并(折叠)为单个边距,其⼤⼩为单个边距的最⼤值 (或如果它们相等,则仅为其中⼀个),这种⾏为称为边距重叠。
1.哪些元素会发⽣外边距重叠问题
(1)情况一:相邻兄弟元素的marin-bottom和margin-top的值发⽣重叠
<!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>Document</title>
<style type="text/css">
div.bfcCls {
width: 300px;
height: 300px;
border: 1px solid black;
}
div.bfcCls div.first {
width: 100px;
height: 100px;
background-color:aqua;
margin-bottom: 50px;
}
div.bfcCls div.second {
width: 100px;
height: 100px;
background-color:orchid;
margin-top: 80px;
float: left;
}
</style>
</head>
<body>
<div class="bfcCls">
<div class="first">
</div>
<div class="second">
</div>
</div>
</body>
<script>
</script>
</html>
(2) 情况二:⽗级和第⼀个/最后⼀个⼦元素的margin合并
<!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>Document</title>
<style type="text/css">
div.bfcCls {
width: 300px;
height: 300px;
background-color:blue;
margin-top: 50px;
padding: 1px;
box-sizing: border-box;
}
div.bfcCls div.first {
width: 100px;
height: 100px;
background-color:darkgreen;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="bfcCls">
<div class="first">
</div>
</div>
</body>
<script>
</script>
</html>
(3)情况三:空的块级元素
<!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>Document</title>
<style type="text/css">
div.bfcCls {
width: 500px;
height: 500px;
background-color:coral;
}
div.bfcCls div.first {
width: 100px;
height: 100px;
background-color:hotpink;
margin-bottom: 50px;
}
div.bfcCls div.second {
margin-top: 20px;
margin-bottom: 20px;
border:1px solid turquoise;
/* padding: 1px; */
box-sizing: border-box;
}
div.bfcCls div.third {
width: 100px;
height: 100px;
background-color: yellowgreen;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="bfcCls">
<div class="first">
</div>
<div class="second">
</div>
<div class="third">