5

I've always thought I understood margins and negative margins but apparently I don't! I've just started a new design and running into problems already.

I have a div (hill3Cont) and another div (hill3Hill) nested inside, and this is the CSS for them.

#hill3Cont
{
    width: 100%;
    background-image: url("images/grass.jpg");
}
#hill3Hill 
{
    margin: -100px 0 0 0;
    height: 600px;
    width: 100%;
    background: url("images/hill3.png") no-repeat center top;
}

I have applied a negative margin to the top of the child div in the hope it will push this content up outside the boundaries of the parent div. But it doesn't, it doesn't move. If I apply a positive margin it pushes the parent div down along with the child inside it.

The only way I can make it behave properly is use a border or overflow hidden on the parent div, but the design won't allow for either of these (I don't want a border and overflow hidden hides the child).

Maybe it's just been a long day and I'm missing something common! Many thanks in advance.

Edit: I have got a solution, I've put a single padding top on the parent div, padding: 1px 0 0 0. It works for my design so I'm happy but still keen to find out what's happening.

Chris
  • 2,630
  • 3
  • 31
  • 58
  • I don't understand why things are working the way they are. After looking at Alexander's solution I see that we have gotten to answers that solve the problem, but no answers as to why yours does not work. Why would adding a border make your version work?! – mrtsherman Apr 25 '11 at 15:32

1 Answers1

5

For child inside parent element use position relative and negative top instead.

http://jsfiddle.net/GEwj3/3/

#hill3Cont
{
    margin-top: 50px;
    width: 200px;
    height: 200px;
    background-color: red;
}
#hill3Hill 
{
    height: 50px;
    width: 100px;
    background: blue;
    position: relative;
    top: -20px;
}
mrtsherman
  • 39,342
  • 23
  • 87
  • 111
  • Still no unfortunately, this is a closer example of mine scenario, I don't have borders (which seemed to fix it) http://jsfiddle.net/GEwj3/1/ The moment I put a border on it fixes it http://jsfiddle.net/GEwj3/2/ – Chris Apr 21 '11 at 21:59
  • 1
    Well I guess I learned a thing or two also. If you use a negative margin the child element apparently cannot float out of and above its parent element. If you want to do this then use position relative with with a negative top offset. http://jsfiddle.net/GEwj3/3/ – mrtsherman Apr 22 '11 at 05:45