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

    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

Rob 230
This was chosen as the best answer

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

Answered over 9 years ago by Rob
  • I especially like the overflow trick. Robert Koritnik over 9 years ago
  • 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. Doug over 9 years ago
  • Yes those scrollbars are probably related to *outline* setting. Anyway. I ended up using overflow. Robert Koritnik over 9 years ago

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.

Answered over 9 years ago by Jens Hedqvist
  • 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 Stephan Hovnanian over 9 years ago
  • 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. Doug over 9 years ago

The full explanation for why it does it:


Answered over 9 years ago by Tony Crockford
  • Great explanation at that website. Doug over 9 years ago