问题
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.)
回答1:
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'".
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/6929874/item-with-margin-top-has-margin-outside-of-containing-box