2017-04-05 27 views
2

我有一個h1標記,當我更改它的margin-top屬性時,它也會移動父元素和祖父元素。任何人都可以解釋爲什麼會發生這種情況,以及如何解決?爲什麼要更改標題標記的邊距會移動其父元素和祖父元素?

如果您注意到,當h1保證金設置爲0 auto時,兩個部分之間具有正確的排水溝。

Pen1

<section></section> 
<section> 
    <div class="notice"> 
     <h1>Our website is currently undergoing construction, please feel free to contact us on social media.</h1> 
    </div> 
</section> 

section{ 
    margin-bottom: 10px; 
    width: 100vw; 
    height: 100vh; 
    background-color: red; 
} 

section:nth-of-type(2){ 
    background-color: blue; 
} 

.notice{ 
    width: 100vw; 
    height: 10vh; 
    text-align: center; 
} 

.notice h1{ 
    margin: 0 auto; 
} 

然而,一旦予設置h1元件具有餘量,這樣做移動父DIV和祖父母節元件。

Pen2

<section></section> 
<section> 
    <div class="notice"> 
     <h1>Our website is currently undergoing construction, please feel free to contact us on social media.</h1> 
    </div> 
</section> 

section{ 
    margin-bottom: 10px; 
    width: 100vw; 
    height: 100vh; 
    background-color: red; 
} 

section:nth-of-type(2){ 
    background-color: blue; 
} 

.notice{ 
    width: 100vw; 
    height: 10vh; 
    text-align: center; 
} 

.notice h1{ 
    margin: 50px auto; 
} 

回答

2

這就是所謂的 「保證金崩潰」。保證金在父母之外崩潰。

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

如果沒有邊框,填充,內嵌的內容,block_formatting_context創建或間隙塊的上邊距從它的第一子塊的邊距,或無邊框分離,填充,內聯內容,高度,最小高度或最大高度將塊的邊緣底部與其最後一個子塊的邊緣底部分開,然後這些邊距將摺疊。 摺疊的邊距最終在父級之外。

一個解決它的辦法是增加overflow: hidden

section{ 
 
\t margin-bottom: 10px; 
 
\t width: 100vw; 
 
\t height: 100vh; 
 
\t background-color: red; 
 
\t overflow: hidden; 
 
} 
 

 
section:nth-of-type(2){ 
 
\t background-color: blue; 
 
} 
 

 
.notice{ 
 
\t width: 100vw; 
 
\t height: 10vh; 
 
\t text-align: center; 
 
} 
 

 
.notice h1{ 
 
\t margin: 50px auto; 
 
}
<section></section> 
 
<section> 
 
\t <div class="notice"> 
 
\t \t <h1>Our website is currently undergoing construction, please feel free to contact us on social media.</h1> 
 
\t </div> 
 
</section>

或者你可以使用padding,而不是margin

section{ 
 
\t margin-bottom: 10px; 
 
\t width: 100vw; 
 
\t height: 100vh; 
 
\t background-color: red; 
 
} 
 

 
section:nth-of-type(2){ 
 
\t background-color: blue; 
 
} 
 

 
.notice{ 
 
\t width: 100vw; 
 
\t height: 10vh; 
 
\t text-align: center; 
 
} 
 

 
.notice h1{ 
 
\t margin: auto; 
 
\t padding: 50px 0; 
 
}
<section></section> 
 
<section> 
 
\t <div class="notice"> 
 
\t \t <h1>Our website is currently undergoing construction, please feel free to contact us on social media.</h1> 
 
\t </div> 
 
</section>

+0

所以基本上,我需要設置父母和祖父母元素的邊距? – Robert

+0

@Robert有很多方法可以解決它。您可以在該部分或標題上使用「頂部」,而不是標題上的邊距。或者你可以在該部分添加「overflow:hidden」。如果這兩種方法都不適合你,還有其他解決方法。 –

+0

好的,謝謝你的信息,鏈接和解決方案。 – Robert

相關問題