5

I have three nested DIV elements like this:

<div id="outer">
    <div id="innerA">
        <div id="innerB">
            This<br/>is<br/>a<br/>multiline<br/>testcase.<br/>
            This<br/>is<br/>a<br/>multiline<br/>testcase.<br/>
        </div>
    </div>
</div>

#innerA has a height of 100% which makes it as big as #outer. #innerB's height is left to be auto so it gets as high as its contents. Now when i set #innerB to have margin-top: 10px for example i would expect that #innerB will get a margin in relation to #innerA. What happens instead is that #innerA gets this margin in relation to #outer.

How is this possible? It seems like this has nothing to do with box-sizing at least its not fixable this way.

Here's the CSS:

#outer {
    width: 500px;
    height: 300px;
    background: yellow;
    overflow: auto;
}

#innerA {
    width: 100%;
    height: 100%;    
    background: green;
}

#innerB {
    margin-top: 10px;
    background: blue;
}

and the fiddle:

http://jsfiddle.net/7e2H5/

(Here i would expect that the green DIV fits the yellow one, and that there are 10px of the green one visible above the blue DIV).

Chris
  • 7,675
  • 8
  • 51
  • 101

4 Answers4

4

Seems like it's a "Margin collapsing" problem. Check the DEMO

I've added padding: 1px 0;

More info: https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing

Just found this: margin-top in a nested div

Community
  • 1
  • 1
Mihey Egoroff
  • 1,542
  • 14
  • 23
  • So there's no way to get around this without changing `#innerA` right? What a mess.. is there any situation where this even makes sense? – Chris Dec 12 '13 at 13:44
  • Accepted this one, because it gives a lot of information on why css acts this way. The answer of @sureshdeepak solved my problem for now but i think i will have to change this again later. – Chris Dec 12 '13 at 14:08
3

This is interesting but I wouldn't say that adding padding is a more appropriate answer.

#innerA {
    width: 100%;
    height: 100%;    
    background: green;
    display: inline-block;
}

Here's a demo on JSFiddle.

I hope this helps!

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
  • Mhm this seems to work best (for now) i fear there will be side effects with this one because the container will have different behaviour when other containers are inside. But for now this is a good solution. – Chris Dec 12 '13 at 13:59
0

I would replace #innerb margin with #innera padding

scooterlord
  • 15,124
  • 11
  • 49
  • 68
0

According to the Mozilla link provided by Chris, adding floats also prevents margins from collapsing:

Add float: left; to #innerA as shown in this fiddle: http://jsfiddle.net/7e2H5/10/

See: https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing

Stephen Done
  • 493
  • 5
  • 13