简体   繁体   中英

Why does overflow:hidden affect background's visibility of a div that has a nested div with top/bottom margin?

I hope the title is not very confusing. As you can see in the example below, there are an outer div and an inner div, I set a margin-top:100px to the inner div. In the "margin area" we can't see the background of the outer div by default. But if you add overflow:hidden to the outer div, the background appears. Can someone explain why this happens?

I hope I have made myself understood here because I'm not a native English speaker.

 $("button").on("click", function() { $(".outer").toggleClass("hidden"); }); 
 div.outer { background: red; width: 100px; } div.outer.hidden { overflow: hidden; } div.inner { margin-top: 100px; background: blue; height: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-1.11.3.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div class="outer"> <div class="inner"></div> </div> <br> <button>toggle</button> </body> </html> 

I believe this is the result of something called margin collapsing .

Essentially, without the overflow, the browser is collapsing the margin-top of the inner element with the margin-top of the container. It's a crappy thing.

When you add overflow, or absolute positioning, or float, the browser's collapse effect does not take place.

From the MDN :

These rules apply even to margins that are zero, so the margin of a first/last child ends up outside its parent (according to the rules above) whether or not the parent's margin is zero.

"A margin needs something to bounce on. Since the parent div has nothing to bounce on, it will bounce on the element above it."

Therefore you should use padding instead of margin. Or set the overflow of the outer div to hidden or auto .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM