2

Please refer to http://jsfiddle.net/NobleWolf/X6qVv/.

I have three divs that are set to the window height by jquery and they have a bottom margin, they're called '.pannel'. Inside each '.pannel' is a child called '.pContent' that has a top padding.

My question is why does the '.pContent' change the parent's top margin when "padding-top: 3%;" is changed to "margin-top: 3%;"

Thank you!

Josh Wyss
  • 135
  • 1
  • 5

2 Answers2

7

It's due to collapsing margins - the top margin of a block level element will always collapse with the top-margin of its first in-flow block level child if there is no border, padding, clearance or line boxes separating them. One way you can prevent this behaviour is by changing the display value of each containing div to inline-block:

http://jsfiddle.net/X6qVv/4/

Adrift
  • 58,167
  • 12
  • 92
  • 90
  • The only things is when changed to inline-block the div is no longer centered by the auto left and right margins. Would there be anything wrong, compatibility issues etc..., with leaving it the original format? – Josh Wyss Jun 16 '13 at 20:39
  • There are other ways - as @staircasebug pointed out you can also create a new block-formatting context by adding `overflow: hidden;` to `.pannel`: http://jsfiddle.net/X6qVv/3/ – Adrift Jun 16 '13 at 20:58
  • `display: flex` on the container also disables collapsing margins. – Philzen Aug 02 '22 at 14:53
3

Margin collapse. See references below for some examples on avoiding it.

https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing http://reference.sitepoint.com/css/collapsingmargins

See fiddle - overflow hidden applied to .pannel http://jsfiddle.net/pTTQQ/

.pannel {
  width: 100%;
  padding-bottom: 10%;
  overflow: hidden;
}

.pContent {
  width: 90%;
  height: auto;
  margin: 0 auto 0 auto;
  margin-top: 3%; /* Why can't this be margin top? */
}
Philzen
  • 3,945
  • 30
  • 46
staircasebug
  • 144
  • 3