2

Learning CSS in earnest, and a bit confused.

I have a table in a div.

.bigdiv {
  background-color: red;
  padding: 10px;
}

table {
  background-color: aquamarine;
  margin-left: 300px;
  margin-bottom: 100px;
  padding: 10px;
}
<div class="bigdiv">
  <table>
    <tr>
      <td>foo</td>
    </tr>
  </table>
</div>

which works as I expect, with a big 110px red swath below the aquamarine box.

But when I take the padding out of the div, the margin-bottom overflows the div, and the visual appearance is an aquamarine box at the edge of a red div.

I'd like to understand the rules behind this behavior. Is this something specific about divs, or does the container generally have to have a nonzero padding in order for the content's margin to appear in the container?

mt_
  • 129
  • 1
  • 9

1 Answers1

1

Margins collapse which means when you have an elemeht with a bottom margin and another one with a top margin below, it will only display the biggest one.

This is true for parent/child margins, too. Only the biggest margin is displayed and that outside the parent.

There are 2 css workarounds:

  • overflow:auto
  • padding:1px

Both css rules can be added to the parent to solve the problem.

For further examples and more explanation you can find something e.g. here: https://css-tricks.com/what-you-should-know-about-collapsing-margins/

The keyword you need to search for is "margin collapsing"

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60
  • 1
    also worth a note that this margin collapse i think only affects block level elements. if he sets his table to `display: inline-block` and removes the padding on the wrapping div he would get the behavior he's expecting – zgood Jun 14 '18 at 17:31
  • @zgood - you beat me to the punch. I did test it and setting to inline-table OR inline-block works. – Bryan Joseph Myers Jun 14 '18 at 17:34
  • @BryanJosephMyers Be careful with inline-block elements. When you put 2 inline-block elements next to eachother they will always have a margin in between which comes from the space or newline in you source because its "inline" and spaces matter – Fuzzyma Jun 14 '18 at 17:39
  • @Fuzzyma - Good point! I have run in to the issue you described before and addressed it by putting both "inline-block" elements on the same line in HTML. – Bryan Joseph Myers Jun 14 '18 at 18:02