margin collapsing 解决

1 ,初始代码以下:html

<body style="border: 2px solid blue;">
  <div id="container" style="height: 200px; background-color: gray; ">
    <p style="margin-top: 0px; height: 20px; background-color: red;">test</p>
  </div>
</body>布局

  效果:flex

 

 

 

2,修改一下p元素的margin-top为100px 以下:spa

<body style="border: 2px solid blue;">
  <div id="container" style="height: 200px; background-color: gray; ">
    <p style="margin-top: 100px; height: 20px; background-color: red;">test</p>
  </div>
</body>orm

  效果以下:htm

 

 

 

p元素的margin彷佛变成了div元素的maginblog

 

3,在p元素前加了内容,代码:作用域

<body style="border: 2px solid blue;">
  <div id="container" style="height: 200px; background-color: gray; ">
  &nbsp;
  <p style="margin-top: 100px; height: 20px; background-color: red;">test</p>
  </div>
</body>io

  效果以下:class

 

 

这下正常了,margin还给p元素了,可是, 由于加了空行,因此距离不是100px了... 不可取的解决方案。

科学的解决方法:

<body style="border: 2px solid blue;">
	<div id="container" style="height: 200px; background-color: gray; overflow: hidden;">
	    <p style="margin-top: 100px; height: 20px; background-color: red;">test</p>
	</div>
</body>

  

 

=====================================================

进入正题: 这是什么缘由,以及如何解决。

缘由分析:   同一个BFC内,垂直方向盒子的上下会出现margin重叠

 

BFC是什么:
BlockFormatting (块级格式化上下文)
能够同时存在不少盒子,独立的布局做用域。固然也只有块级元素能参与转化成BFC。
BFC内部的布局规则
一、内部的Box会在垂直方向,一个接一个地放置。
二、 同一个BFC内,垂直方向盒子的上下会出现重叠
三、每一个元素的 box的左边, 与包含块border box的左边相接触(对于从左往右的格式化,不然相反)。即便存在浮动也是如此。
四、子BFC的区域不会与float box重叠。
五、BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
六、计算BFC的高度时,浮动元素也参与计算(故也能够达到所谓的清除浮动的效果,只要将包裹层转变给BFC)
 
 
如何将一个块级元素转化成BFC?
官方给出了如下几种方式:
一、具备除了float:的其它浮动属性值;
二、定位为absolute或者fixed;
三、display为inlineblock, -cell, -caption, flex, inlineflex
四、overflow不为visible(除非该值已经传播到视口,如 body 会将的值传播到视口,故此状况下,设置该属性不能创建bfc)
相关文章
相关标签/搜索