• css外边距塌陷(合并)


    [1]相邻块元素垂直外边距的合并
    1.当上下相邻的二个块元素相遇时,如果上面的元素有下外边距margin-buttom
    2.下面的元素有上外边距margin-top,则他们之间的垂直间距不是margin-bottom与mtop之和
    3.取二者值中的较大者的这种现象称之为相邻块元素垂直外边距的合并
    解决方法
    尽量只给一个盒子加margin
    在这里插入图片描述

    <style>
            .a1{
                width: 200px;
                height: 200px;
                background-color: aquamarine;
                margin-bottom: 100px;
            }
            .a2{    
                margin-top: 50px;
                width: 200px;
                height: 200px;
                background-color: darkorange;
            }
        </style>
    </head>
    <body>
        <div class="a1"></div>
        <div class="a2"></div>
    </body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    运行结果:
    在这里插入图片描述
    【2】嵌套块元素垂直外边距的合并
    1、对于二个嵌套关系的块元素,如果父元素没有上内边距或边框
    2、父元素的上外边距会与子元素的上外边距发生合并
    3、合并值为二者中的较大者
    解决方法:
    1、可以给父元素定义上边框border-top
    2、可以给父元素定义上内边距padding-top
    3、可以给父元素添加overflow:hidden;
    4、转为行内块元素
    5、设置浮动
    其他:浮动、固定、绝对定位的盒子

    <style>
            .father{
                width: 300px;
                height: 300px;
                background-color: aquamarine;
                margin-top: 100px;
                /* border: 1px solid; */
                /* padding: 1px; */
                overflow: hidden;
            }
            .son{
                margin-top: 150px;
                width: 100px;
                height: 100px;
                background-color: blue;
            }
         </style>
    </head>
    <body>
        <div class="father">
            <div class="son"></div>
        </div>
    </body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    外边距塌陷的运行结果:
    不管是子盒子还是父盒子都会被往下顶;
    子盒子设置了margin-top=100px,会把父盒子往下顶100px,即:坑爹行为
    如果父亲设置了margin-top=200px,则父盒子会往下移动200px
    在这里插入图片描述

    消除塌陷后运行结果:
    在这里插入图片描述

  • 相关阅读:
    Vue Router路由
    2022年9月6号:Yaml语法和JSR303数据校验《SpringBoot第三课的内容》
    二分查找以及扩展
    前端开发:Mac电脑修改hosts文件的方法
    Elasticsearch是如何通过倒排索引来查询数据的
    Python3-提取pdf文件内容的方式,PyPDF2的使用
    学习笔记17--汽车运动控制理论之现代控制理论
    第一章:JDBC操作数据库
    Redis淘汰和过期策略
    【Linux】diff 命令
  • 原文地址:https://blog.csdn.net/lxllxl211/article/details/127415076