外边距合并和嵌套块元素塌陷问题及解决方法

  1. 相邻块元素垂直外边距合并
    * {
        padding: 0;
        margin: 0;
    }
    
    .father {
        width: 300px;
        height: 300px;
        background-color: chartreuse;
        margin-bottom: 100px;
    }
    
    .monther {
        width: 100px;
        height: 100px;
        background-color: chocolate;
        margin-top: 200px;
    }
</style>

<body>
    <div class="father"></div>
    <div class="monther"></div>
</body>
father踹monther一下  离我100px远, monther生气了给father也来了一脚200px,
那  最后俩个块元素相距300px吗?? 事实说话

在这里插入图片描述

                所以垂直外边距会出现合并,结果取大的
                解决方案:当然就是相邻块元素最好只设置一个外边距了
  1. 嵌套块元素塌陷问题
		<style>
    * {
        padding: 0;
        margin: 0;
    }
    
    .father {
        width: 300px;
        height: 300px;
        background-color: chartreuse;
        margin-top: 20px;
    }
    
    .son {
        width: 100px;
        height: 100px;
        background-color: chocolate;
        margin-top: 50px;
    }
</style>

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

在这里插入图片描述

     最后显示结果却是这样  如何解决呢?
     解决方案:给父元素添加边框  (border: 1px solid transparent;)最好设置透明
			  给父元素添加内边距
			  给父元素添加overflow:hidden
			  设置浮动,固定,绝对定位
			  第三种方法最为推荐,这样不影响盒子大小,因为border和padding会撑大盒子

这样就解决了!!!
这样就解决嵌套块元素塌陷问题了!!!尝试一下吧

发布了6 篇原创文章 · 获赞 6 · 访问量 74

猜你喜欢

转载自blog.csdn.net/qq_44755188/article/details/105557889