Search code examples
htmlcssmargins

Item with margin-top has margin outside of containing box


I have something to this effect:

#div {
   background: green; 
   width: 200px;
   height: 100px;
}

h1 {
   margin-top: 100px;
}

(And obviously there is some HTML to go with it.)

Now when viewed in the browser the h1 shows at the very top of the #div and the 100px margin goes on top of the #div.

Can anyone suggest a reason?

(The code is a little too complicated to insert the relevant parts so if no-one can give me an answer then I will post it and maybe someone will spot an error or something.)


Solution

  • Try to add padding instead. I've seen this kind of problem before. If the padding does the the same thing then try putting a container div around but #div and the h1 then add the margin. If you are just wanting to move the h1 down from the #div then padding is your best bet since it will "Push the h1 further into the #div 'box'".