天天看點

CSS之外邊距的重疊問題

垂直外邊距的重疊:

相鄰的垂直方向的外邊距會發生重疊現象

兄弟元素:

兄弟元素之間的相鄰垂直方向的外邊距會取兩者之間的最大值

特殊情況:

一正一負,取兩者和

都為負,取絕對值最大的一邊

父子元素:

父子元素間的相鄰外邊距,子元素的會傳遞給父元素(上外邊距)

父子元素的外邊距的重疊會影響頁面的布局,需要進行處理

解決方案:

1.不使用外邊距,采取

在父元素中,使用内邊距padding-left,然後減高度

2.給父元素添加上邊框,使得父子邊距不重疊(高度應減去邊框寬度)

前提:要保證盒子的大小不變

Demo:

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>外邊距的折疊</title>
    <style>
    .div1,.div2{
        width:200px;
        height:200px;

    }
    .div1{
        background-color: violet;
        margin-bottom:400px;
    }
    .div2{
        background-color: yellow;
        margin-top: 350px;
    }

    .boxOut{
        width:200px;
        height:199px;
        background-color:#bfa ;
        border-top:1px solid #bfa;
    }

    .boxInner{
        width:100px;
        height:100px;
        background-color:yellow;
        margin-top: 99px;
        /* margin-top: 100px;
        margin-left: 50px; */
        /* margin-right:100px; */
    }
    
    </style>
</head>
<body>
    <!-- <div class="div1"></div>
    <div class="div2"></div> -->

    <div class="boxOut">
        <div class="boxInner"></div>
    </div>

</body>
</html>
           

繼續閱讀