P粉1410350892023-08-24 21:55:31
Try using display: inline-block;
on the inner div
. like this:
#outer { width:500px; height:200px; background:#FFCCCC; margin:50px auto 0 auto; display:block; } #inner { background:#FFCC33; margin:50px 50px 50px 50px; padding:10px; display:inline-block; }
P粉1704382852023-08-24 21:55:02
What you actually see is the top margin of the #inner
element collapses to the top edge of the #outer
element, leaving only the #outer
Margins are intact (although not shown in the image). The top edges of the two boxes are flush with each other because their margins are equal.
The following are relevant points from the W3C specification:
You can do any of the following to prevent margins from collapsing:
The above options prevent margin collapse for the following reasons:
The left and right margins behave as you expect because: