I have a div (parent) that contains another div (child). Parent is the first element in body with no particular CSS style. When I set
.child
{
margin-top: 10px;
}
The end result is that top of my child is still aligned with parent. Instead of child being shifted for 10px downwards, my parent moves 10px down.
My DOCTYPE is set to XHTML Transitional.
What am I missing here?
3 answers
point
As stated in the comments by Doug and Jens, this has to do with how margin collapse works when elements follow each other. There are two ways around this. One is to give the parent element a border. The other is to add 'overflow:auto'.
- I especially like the overflow trick.
- I'd be cautious in using overflow; I've seen strange results (appearing and disappearing scrollbars). I still prefer padding the top of the .parent.
- Yes those scrollbars are probably related to *outline* setting. Anyway. I ended up using overflow.
points
Yes, try adding padding to the parent element instead. I've stumbled across that "feature" a couple of times before. A clean margin pointing towards the body-element makes everything shift downwards.
Maybe someone has a techical explanation, I suppose it has to do with some margin-collapse issue.
- I agree; I try to stay away from padding just because it isn't as accurate as margin, but in a case like this one above you're better off with padding. or position:absolute the child div
- Margin-top tells the element how far away it should be from elements that precede it. The .parent div does not "precede" the .child div; it surrounds it, and they share a margin. In this case, nothing precedes the .child div, but since the body element is treated differently, the .child is spaced from the edge of the body. What you want is to pad the top of the .parent. There is nothing "inaccurate" about padding. I would avoid absolute positioning, which removes the element from the flow, unless absolutely necessary.
point
The full explanation for why it does it:
http://complexspiral.com/publications/uncollapsing-margins/
- Great explanation at that website.
