Chaim
Chaim

Reputation: 2149

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.)

Upvotes: 17

Views: 9012

Answers (3)

Dean Tambling
Dean Tambling

Reputation: 31

I was able to solve this problem by making all of my header tags (h1-h6) display: inline-block;. As inline elements with margins, they can overflow like that, but as inline blocks they behave a little more nicely with others.

Upvotes: 3

Jerome Cance
Jerome Cance

Reputation: 8183

This is not related to the H1 tag. This is what we call margin collapse.

You can find a post about this subject here : http://reference.sitepoint.com/css/collapsingmargins

you have several solutions :

  • use padding instead
  • add overflow: auto on your parent div
  • add transparent top border to the parent div

Upvotes: 17

Howdy_McGee
Howdy_McGee

Reputation: 10643

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'".

Upvotes: 1

Related Questions