Grow your CSS skills. Land your dream job.

why is my internal div causing the outer divs to move with it.

  • # December 27, 2012 at 1:29 pm

    hi everyone.

    i am a bit confused about why my div are behaving the way they do and would really like some advice.

    i have two div elements on my page.

    . the main page div with a background image.

    and a small div that will be contained within the main div i.e;
    div id=body

    div id=body_wrapper

    p testing bodywrap p

    END div body WRAPPER

    END div id body

    my problem is this; when i code the wrapper div and give it a margin-top of 150px and a background colour , it drags the main page div down with it. i am not clear why it behave that way.

    i have enclose the code : u will note that the test body wrap div is dragging down the main page div; the main divs background colour should cover the whole page and not get dragged down with a div that is contained within it.

    http://codepen.io/joe/pen/GJbxk

    warm regards

    Andreea

    # December 27, 2012 at 1:43 pm

    Is that what you’re looking for?

    http://codepen.io/kevin11189/pen/Alkda

    # December 27, 2012 at 2:06 pm

    Andreea,
    That’s the way margins collapse. [Here's an article](http://complexspiral.com/publications/uncollapsing-margins/ “uncollapsing margins”) that may help explain what’s happening.

    There are couple of things you can do. As kevin showed, you could zero the top margin on the #body-wrapper div and push it into place using padding on the #body div. But there are few other things that can be done, which may make more sense.

    You can apply a top padding or top border (or both, but not necessary) to #body and that will give #body-wrapper’s margin something to ‘push’ against.

    You could also add overflow: hidden to #body. This will change it’s block formatting context and #body-wrapper’s margin again will work as you had hoped.

    A couple of notes. One, a wrapper is usually the outmost element – it seems strange to have #body-wrapper inside of #body. Two, id’ing a div to #body just adds confusion considering the encompassing element has the same name. Three, in this example the #body div is not even needed. Just apply the background image to the body element. Four, there’s really no reason to comment the start of a particular div when it has an id.

    [Here's a fork](http://codepen.io/wolfcry911/pen/KBbLH) of your pen cleaned up a bit, using my last suggestion.

    # December 27, 2012 at 3:04 pm

    hello

    kevin11189 and wolfcry911

    thank you so much for your kind advice and assistance. i will read the article in detail and try and understand why div margins collapse.

    my warmest thanks.

    warm regards

    Andreea

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

You must be logged in to reply to this topic.

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