Grow your CSS skills. Land your dream job.

Margin Extends Beyond Parent

  • # October 23, 2010 at 11:28 pm

    Let’s say I have a parent div that contains an element with a top margin. Why does the margin from the child element extend beyond the top of the parent? The child element still appears at the top-left of it’s parent while it appears that the parent element has the margin. How come the child is not constrained to it’s parent. If the child’s top margin was 20px, I would expect the child element to start 20px from the top it’s parent.

    # October 24, 2010 at 12:38 am

    try putting a position: relative to the parent and position: absolute to the child.

    # October 24, 2010 at 3:05 pm

    because that what the spec states? Add padding or border to the parent to give the the child element’s margin something to ‘push’ against.

    Visit http://www.complexspiral.com/publications/uncollapsing-margins/ for a better understanding

    # October 24, 2010 at 9:36 pm

    Thanks wolfcry…I can’t imagine an article that addressed the problem I was having more accurately. In fact, the instance which finally moved me to make this post was actually the h1 inside a header div :)

    At least now I understand why; I’m not sure I like it, but at least I understand it and know how to work around it.

    # April 1, 2013 at 12:09 am

    I’ve had issues with this in the past and, while I understand why it works this way, I still think it’s kind of weird. I’m not sure I like that the browser “assumes” what I’m wanting instead of just letting me define exactly what I want. Something else that would be a good addition to the spec would be “box-sizing: margin-box;”. I think it would be very useful to say, “I want a box that’s 100px by 100px regardless of how much padding, border, and margin I put on it.” Anyway, just some thoughts on this 2.5 year old post!

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".