2017-02-25 135 views
1

如果您在第一個框(red_box)上放置了一個保證金頂部,它將拉動或影響包含框(容器)。爲什麼?HTML和CSS ---保證金問題

.red_box { 
 
    background-color: red; 
 
    margin-top: 10px; 
 
    margin-right: 20px; 
 
    margin-bottom: 20px;` 
 
    margin-left: 40px; 
 
    height: 100px; 
 
    width: 300px 
 
} 
 

 
.green_box { 
 
    background-color: green; 
 
    margin-top: 40px; 
 
    margin-right: 20px; 
 
    margin-bottom: 20px; 
 
    margin-left: 40px; 
 
    height: 100px; 
 
    width: 300px 
 
} 
 

 
.container { 
 
    width: 500px; 
 
    height: 500px; 
 
    background-color: yellow; 
 
}
<div class="container"> 
 
    <div class="red_box"> 
 
    red box 
 
    </div> 
 
    <div class="green_box"> 
 
    green box 
 
    </div> 
 
</div>

回答

2

這樣做的原因行爲是margin collapsing

在CSS中,兩個或多個框的相鄰邊緣(這可能會或可能不會是兄弟姐妹)可結合形成單一的保證金。

可以防止它與overflow規則對.container

.red_box { 
 
    background-color: red; 
 
    margin-top: 10px; 
 
    margin-right: 20px; 
 
    margin-bottom: 20px;` 
 
    margin-left: 40px; 
 
    height: 100px; 
 
    width: 300px; 
 
} 
 

 
.green_box { 
 
    background-color: green; 
 
    margin-top: 40px; 
 
    margin-right: 20px; 
 
    margin-bottom: 20px; 
 
    margin-left: 40px; 
 
    height: 100px; 
 
    width: 300px 
 
} 
 

 
.container { 
 
    width: 500px; 
 
    height: 500px; 
 
    background-color: yellow; 
 
    overflow: hidden; /* <-- this prevents margin collapsing */ 
 
}
<div class="container"> 
 
    <div class="red_box"> 
 
    red box 
 
    </div> 
 
    <div class="green_box"> 
 
    green box 
 
    </div> 
 
</div>