margin塌陷 其实就是一个bug。很多人在开发的时候都会遇到。但是却不知道是怎么产生的。
一下代码演示margin塌陷
参考:
这里是一个父子关系的div
<div class="fa"> <div class="ch"></div> </div>
首先我们设置一下这个2个div 的css样式
.ch{ margin-left: 100px; /*左边距离父标签100px*/ width: 100px; height: 100px; background-color: red; } .fa{ margin-left: 100px; margin-top: 100px; width: 200px; height: 200px; background-color: blue; }
一下是运行效果
屏幕快照 2018-06-22 上午10.23.01.png
这么看是没有任何问题的
如果我门在加上margin-top: 100px;顶部距离父标签100px.ch{ margin-left: 100px; /*左边距离父标签100px*/ margin-top: 100px;/*顶部距离父标签100px*/ width: 100px; height: 100px; background-color: red; }
屏幕快照 2018-06-22 上午10.23.01.png
效果却并没有想我们预期的那样子试图顶部距离父标签100px
这个现象就是margin塌陷
要解决这个问题有2个方法:
第一个(强硬手段,适合外包)特点:简单粗暴
我们可以直接设置父标签border-top: 1px solid yellow;
.fa{ margin-left: 100px; margin-top: 100px; width: 200px; height: 200px; background-color: blue; border-top: 1px solid yellow; }
效果图:
屏幕快照 2018-06-22 上午10.45.22.png
效果达到
说明border-top: 1px solid yellow,可以解决这个问题,yellow颜色只是我胡乱设置的。不必在意。但是在开发的还是设置和背景颜色一样比较好。
第二方法:简称bfc (block format context)块级格式化上下文。(专业用该方法)
注意:如果要使用这个,一定要对其要有一定的理解。不然就算解决了margin塌陷, 也会出现其他的问题。
解释一下:
你可这么理解,css其实就是把标签当成是一个“块”或者说是“盒子”。每一个盒子都有一摸一样的渲染规则。就是你设置什么属性,它就会按照你写的代码,按照你的方式图形化出来。
bfc就是通过一种手段,改变其中一个或者多个盒子中的渲染规则,就是不让他按照传统的语法来,那么这些盒子就会按照另一套语法来。其实bfc改变的语法规则很少,百分之一可能都不到,但是就是这很少的这部分可以解决这个问题。
如何触发bfc
display: inline-block;
position: absolute;
float: right/left;
overflow: hidden;
只要在父标签设置了这几个属性的其中一个就可以出发bfc,其实使用起来很简单,只是使用这个,一定要知道,这几个属性的含义,针对性的使用。
.fa{
/*display: inline-block;*/ 改变标签的类型
position: absolute; 对象脱离常规流
/*float: right/left;*/ 设置元素浮在右边/左边
/*overflow: hidden;*/ 超出的部分隐藏
margin-left: 100px;
margin-top: 100px;
width: 200px;
height: 200px;
background-color: blue;
}
网友评论