父元素和子元素的margin-top问题

父元素和子元素的margin-top问题

   父元素盒子包含子元素盒子,给父元素设置margin-top有效果,但给子元素设置margin-top,父元素和子元素的距离没有变化,但是父元素盒子会往下走子元素的margin-top的值。这个就是典型的margin折叠问题。

原理:margin折叠(Collapsing Margins)
毗邻的两个或多个外边距 (margin) 在垂直方向会合并成一个外边距。
这里的毗邻指没有上下padding-top,padding-bottom,border-top,border-bottom,元素内容不为空。

html代码

<div class="father">        
	<div class="son"></div>    
</div>

css代码

* {padding: 0;margin: 0;}        
.father {height: 400px;width: 400px; background-color:pink; margin-top: 100px;}        
.son {height: 200px;width: 200px;background-color: skyblue;margin-top: 100px;}

效果
在这里插入图片描述
分析
本例中的father盒子和son盒子是父子级关系,同时设了padding-top,属于了毗邻的范畴,出现了margin重叠,所以会出现子级元素和父级元素这件没有距离,父级却一起走了下来的问题。
解决方法
1.父元素添加padding-top样式;
2.父元素添加overflow:hidden样式;
3.父元素或子元素浮动;
4.给父元素添加boarder(看需求而定);
5.为父元素或子元素绝对定位;
6.在子元素前添加子div并设置height:1px和overflow:hidden样式(如果添加的是inline-block元素,需要改display为block)。
修正后
在父元素添加padding-top。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41157223/article/details/83614731