块级格式化上下文 BFC(Block Format Context)
BFC:一个独立的渲染区域,外面的元素不会影响到里面布局,里面的元素也不会影响到外面的布局。在BFC中,每一个元素左外边与包含块的左边相接触(对于从右到左的格式化,右外边接触右边)
触发BFC的方式:
float:不为none;
position: absolute或fixed
display: inline-block table-cell table-caption flex inline-flex
overflow: 不为visible
浮动float
当为某一个元素添加float:left/right时,该元素便脱离文档流,我们将之称为浮动。浮动的作用通常是使多个块级元素排列在一行,浮动还可以产生文字围绕效果。
缺点:容易产生高度塌陷问题
高度塌陷:
在父元素中如果不设置固定的宽高,则默认被子元素撑开,如果子元素浮动,那么就会发生父元素高度塌陷,导致页面布局混乱。
*解决方法(清除浮动方法):
(1)给父级设置高度;
(2)触发父元素的BFC:给父元素添加overflow:hidden;
<style>
.parent{
overflow: hidden;
border: 1px solid #CCC;
}
.box1{
width: 100px;
height: 100px;
background-color: yellow;
float: left;
}
.box2{
width: 150px;
height: 150px;
background-color: blue;
float: left;
}
.box3{
width: 200px;
height: 200px;
background-color: pink;
}
</style>
<div class="parent">
<div class="box1"></div>
<div class="box2"></div>
</div>
<div class="box3"></div>
(3)额外标签法:在浮动元素后面添加一个额外的标签并设置clear:both;
<style>
.box1 {
width: 100px;
height: 100px;
background-color: yellow;
float: left;
}
.box2 {
width: 150px;
height: 150px;
background-color: blue;
float: left;
}
.other{
clear: both;
}
.box3 {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
<div class="parent">
<div class="box1"></div>
<div class="box2"></div>
<div class="other"></div>
</div>
<div class="box3"></div>
(4)使用after伪元素清除浮动
<style>
.box1 {
width: 100px;
height: 100px;
background-color: yellow;
float: left;
}
.box2 {
width: 150px;
height: 150px;
background-color: blue;
float: left;
}
.box3 {
width: 200px;
height: 200px;
background-color: pink;
}
.clearfix::after{
content: '';
width: 0;
height: 0;
display: block;
clear: both;
visibility: hidden;
}
.clear{
*zoom: 1;
}
</style>
<div class="parent clearfix">
<div class="box1"></div>
<div class="box2"></div>
</div>
<div class="box3"></div>
(5)使用before和after双伪元素清除浮动
<style>
.box1 {
width: 100px;
height: 100px;
background-color: yellow;
float: left;
}
.box2 {
width: 150px;
height: 150px;
background-color: blue;
float: left;
}
.box3 {
width: 200px;
height: 200px;
background-color: pink;
}
.clearfix::after,.clearfix::before{
content: '';
display: table;
}
.clearfix::after{
clear: both;
}
.clear{
*zoom: 1;
}
</style>
<body>
<div class="parent clearfix">
<div class="box1"></div>
<div class="box2"></div>
</div>
<div class="box3"></div>
</body>