块元素存在的问题
问题一: margin合并问题(垂直外边距重叠)
在为两个相邻的块级元素设置margin(外边距) 会发现一个问题就是两个元素之间的距离并不是1+1=2; 选择margin最大的作为两个元素的间距(当两个元素margin相等时 任选其一)
.box1{
width: 200px;
height: 200px;
background-color: red;
margin-bottom: 30px;
}
.box2{
margin-top: 30px;
width: 200px;
height: 200px;
background-color: lightgreen;
}
<div class="box1"></div>
<div class="box2"></div>
问题二: margin塌陷问题
在父子元素嵌套的情况下 为子元素设置垂直方向的margin 会导致父子元素同时脱离原本位置
设置前
.box1{
width: 200px;
height: 200px;
background-color: red;
}
.box2{
width: 100px;
height: 100px;
background-color: lightgreen;
}
<div class="box1">
<div class="box2"></div>
</div>
设置后
.box1{
width: 200px;
height: 200px;
background-color: red;
}
.box2{
margin-top: 30px;
width: 100px;
height: 100px;
background-color: lightgreen;
}
<div class="box1">
<div class="box2"></div>
</div>
问题二: 高度塌陷问题
仅为父元素设置宽度 其高度由子元素决定时 当子元素进行浮动时 父元素高度为0
浮动前
.box1{
width: 400px;
background-color: red;
}
.box2{
width: 100px;
height: 100px;
background-color: lightgreen;
}
.box3{
width: 100px;
height: 100px;
background-color: lightcoral;
}
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
浮动后
.box1{
width: 400px;
border: 5px solid black;
background-color: red;
}
.box2{
float: left;
width: 100px;
height: 100px;
background-color: lightgreen;
}
.box3{
float: left;
width: 100px;
height: 100px;
background-color: lightcoral;
}
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
产生问题的原因
margin合并与margin塌陷是根据CSS2的规范 浏览器在计算块元素与块元素垂直外边距时一定会出现的情况(CSS2就是这么规定的我也没有办法)
高度塌陷是因为子元素浮动会脱离当前文档布局 导致父元素无法准确的计算自身高度所形成的
BFC
块级格式化上下文(Block Formatting Context)是一种规则 通过使用该规则可以规定一个块元素内部子元素与子元素之间的关系与它们的排列顺序
BFC还可以将一个块元素的内部与外部隔绝开了 形成一个独立的区域
如何为元素设置BFC
区块格式化上下文 - CSS:层叠样式表 | MDN (mozilla.org) 我就直接贴官方文档了 毕竟更全
使用BFC解决margin合并的问题(垂直外边距重叠)
将任意一个元素放入另一个元素中并将该元素设置BFC规则
.box{
width: 100px;
height: 100px;
background-color: red;
margin-bottom: 20px;
}
.box1{
margin-top: 20px;
width: 100px;
height: 100px;
background-color: blue;
}
.small{
float: left;
}
<div class="box"></div>
<div class="small">
<div class="box1"></div>
</div>
但是如果是两个元素在被使用BFC规则元素内设置垂直外边距 仍然会发生垂直外边距折叠的情况
使用BFC解决margin塌陷的问题(垂直外边距重叠)
将父元素设置为BFC
.box{
float: left;
width: 200px;
height: 200px;
background-color: red;
}
.box1{
margin-top: 30px;
width: 100px;
height: 100px;
background-color: blue;
}
.small{
float: left;
border: 5px solid black;
}
<div class="box">
<div class="box1"></div>
</div>
使用BFC解决高度塌陷问题
.box{
float: left;
width: 300px;
background-color: red;
}
.box1{
width: 100px;
height: 100px;
background-color: blue;
}
.box2{
width: 100px;
height: 100px;
background-color: green;
}
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
当然以上问题解决的方式并不唯一 但我只是使用BFC这种方式来解决问题
注
该文章仅仅是学习过程的中理解,如果存在问题,欢迎提出与讨论
参考资料
MDN