Reputation: 31753
The title says it all. I went through the MDN page on margin collapsing, and from what I read don't see what would prevent marin collapsing in that case. You can see it in action below, with the orange box being 82px heigh (4*20+2), while I'd like it to be 22px heigh (20+2). What am I missing?
.outer { border: 1px solid orange }
.inner { margin-bottom: 20px }
<div class="outer">
<div class="inner"><table></table></div>
<div class="inner"><table></table></div>
<div class="inner"><table></table></div>
<div class="inner"><table></table></div>
</div>
Upvotes: 3
Views: 71
Reputation: 19485
From Mastering margin collapsing:
Margin collapsing occurs in three basic cases:
[…]
Parent and first/last child: If there is no border, padding, inline part, block formatting context created, […], then those margins collapse.
Then, the Block formatting context article says:
A block formatting context is created by at least one of the following:
[…]
- anonymous table cells implicitly created by the elements with
display: table
,table-row
,table-row-group
,table-header-group
,table-footer-group
(which is the default for HTML tables, table rows, table bodies, table headers and table footers, respectively), orinline-table
So a <table>
creates a block formatting context. This is why the margins don’t collapse. You can change the <table>
s into <div>
s with display: table;
or display: inline-block;
(which also creates a block formatting context); this will prevent margin collapsing, too:
.outer { border: 1px solid orange }
.inner { margin-bottom: 20px }
.inner > div { display: table }
<div class="outer">
<div class="inner"><div></div></div>
<div class="inner"><div></div></div>
<div class="inner"><div></div></div>
<div class="inner"><div></div></div>
</div>
Upvotes: 3
Reputation: 4821
What makes tables special in this case is the display property they receive. If you define the tables as display block instead, you'll see the margin collapsing in action.
.outer { border: 1px solid orange }
.inner { margin-bottom: 20px }
table { display: block }
<div class="outer">
<div class="inner"><table></table></div>
<div class="inner"><table></table></div>
<div class="inner"><table></table></div>
<div class="inner"><table></table></div>
</div>
I don't believe this question is a duplicate, but this is a relevant question on the topic:
Why doesn't a <table>'s margin collapse with an adjacent <p>?
Specifically, check out the link here:
https://www.w3.org/TR/CSS21/box.html#collapsing-margins
margin-top margin-bottom Applies to: all elements except elements with table display types other than table-caption, table and inline-table
Upvotes: 1