子DIV块中设置margin-top时影响父DIV块位置问题

相信很多前端同学在做页面开发的时候都遇到过这样的问题。给一个div内部的div设置一个margin-top,结果它的父级跟着它一起下移了。如下面的代码

.a {
    100px;
    height:100px;
}
.b {
    50px;
    height:50px;
    margin-top:10px;
}

<div class="a">
    <div class="b"></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合并而没有考虑父级和子集的合并。我们一定要注意,嵌套也属于毗邻的哟。

那么怎么解决这个问题呢?这里提供这样几种方法:

  • 让父级具有“包裹性”
    • 将父级over-flow设为hidden
    • 将父级display设为inline-block
    • 将父级float或absolute
  • 改变父级的结构
    • 给父元素设置padding
    • 给父元素设置透明border
原文地址:https://www.cnblogs.com/huyuzhu/p/8350208.html