3

Check this extremely simple html structure. One div inside another, the inner (green) div has margin-top: 100px, the outer (red) div has no margin-top. The outer div is twice (200px) as high as the inner div (100px).

So what would you expect the result to look like? If you're like me, you get the opposite of what you'd naturally expect to get.

My question is NOT how to prevent this. My question is WHY ist this happening this way consistently across all browsers? I mean, this obviously must be the way it's inteded to work, but to me it's strongly counter-intuitive.

.red {
    background-color: #a00;
    height: 200px;
}

.green {
    background-color: #0a0;
    margin-top: 100px;
    height: 100px;
}
<div class="red">
    <div class="green"></div>
</div>

http://jsfiddle.net/connexo/7txnoj7m/

connexo
  • 53,704
  • 14
  • 91
  • 128
  • What you are trying to achieve? – shanidkv Jan 27 '15 at 10:46
  • what would you expect to happen as this seems reasonable to me – atmd Jan 27 '15 at 10:48
  • What I'm trying to achieve is to understand why rendering it the way browsers do makes sense? – connexo Jan 27 '15 at 10:48
  • 1
    @You feel it's reasonable that margin-top of child elements does not apply inside the parent, but bubble up to the parent? – connexo Jan 27 '15 at 10:49
  • @pete I'm not talking two block level elements next to each other (in that case it obviously makes sense). I'm talking exactly the example structure of one block level element with no margins containing an element with margin-top. – connexo Jan 27 '15 at 10:55
  • 1
    @connexo I think this explains it very well [Answer](http://stackoverflow.com/a/1394795/2259322). – Ruddy Jan 27 '15 at 10:59
  • in my humble opinion it makes sense. you could always use position:relative and top:100px insteed of margin to achieve what I think you did expected, but margin should apply to the parent element as it's not a distance between child and parent element. – Alvaro Menéndez Jan 27 '15 at 11:00

2 Answers2

2

Its normal way of rendering and it is called margin collapsing. More you can read here

Glorifind
  • 402
  • 6
  • 20
  • Eric Meyer himself has written an article about it where even he admits that this behaviour may come a bit unexpected. "In the majority of cases, margin collapsing delivers the types of layout results we want. It's only in those cases where we want margins to be "contained" by other elements that things can go a bit awry. Thanks to the way CSS is written, however, there are ways to overcome the unwanted collapsing. By associating either padding or a border with an element, it will "contain" the margins of descendant elements." http://www.complexspiral.com/publications/uncollapsing-margins/ – connexo Jan 27 '15 at 12:24
0

I think its a parent/child dependency issue. The position of both Divs are default : 'static'. So the red Div is behind the green Div which has the margin-top.

Arthur Leh
  • 21
  • 5