margin-top影响父级位置解决方案
相信很多前端同学在做页面开发的时候都遇到过这样的问题。给一个div内部的div设置一个margin-top,结果它的父级跟着它一起下移了。如下面的代码
.
.parent{
width:100px;
height:100px;
background:#f5f5f5;
}
.son{
width:50px;
height:50px;
margin-top:10px;
background:pink
}
<div class="parent">
<div class="son"></div>
</div>
效果是这样的
但是其实我们期望的效果是这样的
为什么会产生这样的效果呢?这要谈到css的盒模型margin的合并问题
css在盒模型中规定
In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin. 所有毗邻的两个或更多盒元素的margin将会合并为一个margin共享之。毗邻的定义为:同级或者嵌套的盒元素,并且它们之间没有非空内容、Padding或Border分隔。
其实很多小伙伴都知道css有这样一个规定。只是我们只关注了相邻div之间的margin合并而没有考虑父级和子集的合并。我们一定要注意,嵌套也属于毗邻的哟。
另一种解释:
这个问题发生的原因是根据规范,一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会 和其内部文档流中的第一个子元素的上边距重叠。
再说白点就是:父元素的第一个子元素的上边距margin-top如果碰不到有效的border或者padding.就会不断一层一层的找自 己“领导”(父元素,祖先元素)的麻烦。只要给领导设置个有效的 border或者padding就可以有效的管制这个目无领导的 margin 它越级,假传圣旨,把自己的margin当领导的margin执行。
那么怎么解决这个问题呢?这里提供这样几种方法:
让父级具有“包裹性”:
- 将父级over-flow设为hidden
- 将父级display设为inline-block
- 将父级float或absolute
改变父元素结构
- 给父元素设置padding
- 给父元素设置透明border
改良后代码:
.parent{
width:100px;
height:100px;
background:#f5f5f5;
overflow: hidden;
/* border: 1px solid rgb(255,255,255,1); */
/* float: left; */
/* display: inline-block; */
/* position: absolute;*/
/*将margin-top换为 padding-top:10px*/
}
.son{
width:50px;
height:50px;
margin-top:10px;
background:pink
}
<div class="parent">
<div class="son"></div>
</div>
效果均已达到期望值。