Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why display:inline-block can prevent margins collapse? [duplicate]

Tags:

html

css

margin

Show a margins collapse here.

.ct1{
background: red;
margin:40px;
border:1px solid;width:100%;
}

.ct2{
background: pink;
margin:40px;
border:1px solid;width:100%;
}
<div class="ctbox">
<div class="ct1">first</div>
<div class="ct2">second</div>
</div>

There will be a margins collapse between two divs ct1 and ct2,the distance between them is not 40px+40px = 80px ,instead of 40px.

Now i add a css statement display:inline-block; in ct1 or ct2,the distance between them will become 80px,the margins collapse dispear.Why display:inline-block; can prevent margins collapse ?

like image 896
showkey Avatar asked Oct 22 '25 18:10

showkey


1 Answers

From this rule, Collapsing Margins

  • Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
  • Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
  • Margins of inline-block boxes do not collapse (not even with their in-flow children).

...

like image 172
Derek Wang Avatar answered Oct 24 '25 08:10

Derek Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!