1. <head>
    2. <meta charset="UTF-8">
    3. <title>嵌套块元素外边距塌陷</title>
    4. <style>
    5. .father{
    6. width: 500px;
    7. height: 600px;
    8. background-color: deeppink;
    9. margin-top: 100px;
    10. /*overflow: hidden;*/
    11. /*border: red 2px solid;*/
    12. /*padding-top: 1px;*/
    13. }
    14. .son{
    15. width: 200px;
    16. height: 200px;
    17. background-color: blue;
    18. margin-top: 200px;
    19. }
    20. </style>
    21. </head>
    22. <body>
    23. <div class="father">
    24. <div class="son"></div>
    25. </div>
    26. </body>

    image.png
    问题说明:

    • 当儿子有上外边距时,如果父亲也有上外边距,这时会取较大者的值作为父亲的上外边距,儿子就padding-top值就为0了。(如上图)。

    解决方法:

    • 注释中的都是解决办法;
    • 为父亲加一个边框、上内边距都可以解决;
    • 像注释中加 overflow:hidden 属性;
    • 浮动、固定、绝对定位的盒子不会有塌陷问题。

    image.png