Please look at the following example: https://jsfiddle.net/9wbm179c/
The margin-top:50px;
is making this ugly gap between body and .outter
. Just read the code and this message again: between body and .outter
... Isn't it should be making the gap between .inner and .outter
?
html, body { padding: 0; margin: 0; } body { background: #777; } .outter { background: #099; text-align: center; } .inner { background: #ff0; width: 400px; height: 150px; margin: 0 auto; margin-top: 50px; }
<div class="outter"> <div class="inner"> </div> </div>
What you're seeing is called "margin collapse." https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
Parent and first/last child - If there is no border, padding, inline content, block_formatting_context created or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
You can address it a number of ways. One way is by using overflow:hidden;
on the parent element .outter
. You could also use padding-top: 50px
on .outter
instead of margin-top
on .inner
html,body { padding:0; margin:0; } body { background:#777; } .outter { background:#099; text-align:center; overflow: hidden; } .inner { background:#ff0; width:400px; height:150px; margin:0 auto; margin-top:50px; }
<div class="outter"> <div class="inner"> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.