i have h1
tag that, when change margin-top
property, moves parent , grandparent elements well. can explain why occur , how fix it?
if notice, when h1
margin set 0 auto
2 sections have correct gutters between them.
<section></section> <section> <div class="notice"> <h1>our website undergoing construction, please feel free contact 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; }
however, once set h1
element have margin, doing moves parent div , grandparent section elements.
<section></section> <section> <div class="notice"> <h1>our website undergoing construction, please feel free contact 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; }
that's called "margin collapse". margin collapsing outside of parent.
https://developer.mozilla.org/en-us/docs/web/css/css_box_model/mastering_margin_collapsing
if there no border, padding, inline content, block_formatting_context created or clearance separate margin-top of block margin-top of first child block, or no border, padding, inline content, height, min-height, or max-height separate margin-bottom of block margin-bottom of last child, margins collapse. the collapsed margin ends outside parent.
one way fix add overflow: hidden
parent
section{ margin-bottom: 10px; width: 100vw; height: 100vh; background-color: red; overflow: hidden; } section:nth-of-type(2){ background-color: blue; } .notice{ width: 100vw; height: 10vh; text-align: center; } .notice h1{ margin: 50px auto; }
<section></section> <section> <div class="notice"> <h1>our website undergoing construction, please feel free contact on social media.</h1> </div> </section>
or can use padding
instead of margin
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: auto; padding: 50px 0; }
<section></section> <section> <div class="notice"> <h1>our website undergoing construction, please feel free contact on social media.</h1> </div> </section>
Comments
Post a Comment