<div class="outer">
<div class="inner"></div>
</div>
.outer { /* 没有高度,由子元素撑开 */
border: 10px solid #f00;
}
.inner {
width: 100px;
height: 100px;
background-color: pink;
float: left; /* 浮动脱标,outer 没有高度,所以塌陷 */
}
46-1.png
BFC 块级格式化环境
BFC
是一个 css 中的一个隐含属性,可以为一个元素开启BFC
,该元素就会变成一个独立的布局区域-
元素开启
BFC
后的特点:- 开启
BFC
的元素不会被浮动元素所覆盖 - 开启
BFC
的元素 子元素和该元素外边距不会重叠 - 开启
BFC
的元素可以包含浮动的C子元素
- 开启
-
通过一些特殊方式来开启元素的
BFC
:设置浮动元素 (不推荐,因为自己也脱标了)
将元素设置为行内块元素 (不推荐,如果本身就是独占一行)
-
将元素的
overflow
设置为一个非visible
的值常用的方式 为元素设置
hidden
.outer {
border: 10px solid #f00;
overflow: hidden;
}
46-2.png
触发 BFC
不会被浮动元素覆盖
<div class="box1"></div>
<div class="box2"></div>
.box1 {
width: 100px;
height: 100px;
background-color: red;
float: left;
}
.box2 {
width: 100px;
height: 100px;
background-color: green;
}
46-3.png
.box2 {
overflow: hidden;
}
46-4.png
触发 BFC
该元素和子元素外边距不会重叠
<div class="box1">
<div class="box11"></div>
</div>
.box1 {
width: 100px;
height: 100px;
background-color: red;
/* overflow: hidden; */
}
.box11 {
width: 30px;
height: 30px;
background-color: skyblue;
margin-top: 50px;
}
46-5.png
.box1 {
overflow: hidden;
}
46-6.png
清楚浮动 clear
- 可选值
- left:清除左侧浮动元素对当前元素的影响
- right:清除右侧浮动元素对当前元素的影响
- both:清除影响较大那侧
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
.box1 {
width: 100px;
height: 100px;
background-color: red;
float: left;
}
.box2 {
width: 300px;
height: 300px;
background-color: green;
float: right;
}
.box3 {
width: 120px;
height: 120px;
background-color: skyblue;
clear: left;
}
46-7.png
clear: left
实际上是为该元素添加了一个上外边距,这外边距的距离取决于浮动元素的高度。
.box3 {
clear: right;
}
right 同理
46-8.png
这里 both
也是和上图一样的结果,右侧的影响较大。
伪元素-- 高度塌陷
<div class="box1">
<div class="box2"></div>
<div class="box3">haha</div>
</div>
.box1 {
border: 10px solid red;
}
.box2 {
width: 100px;
height: 100px;
background-color: green;
float: left;
}
46-9.png
box3 因为有内容所以撑起了box1,因为是文本,所以会环绕在浮动元素(不然就被浮动元素覆盖了)
.box3 {
clear: both;
}
46-10.png
相当于给 box3 上外边距,边距取决于浮动元素的高度。(清除了浮动,就不会环绕在周边,所以 haha 的位置在正下方)
把文本删了
<div class="box3"></div>
46-11.png
但是这里会加了一个与布局无关的标签。
所以伪元素来了
.box1::after {
content: '';
display: block; /* 伪元素是行内元素 */
clear: both;
}
46-12.png
伪元素--外边距
<div class="box1">
<div class="box11"></div>
</div>
.box1 {
width: 150px;
height: 150px;
background-color: red;
}
.box1::before {
content: '';
display: table;
}
.box11 {
width: 50px;
height: 50px;
background-color: skyblue;
margin-top: 50px;
}
46-13.png
最终版本
.clearfix::before,
.clearfix::after {
content: '';
display: table;
clear: bot;
}
<div class="box1 clearfix"></div>