Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird CSS behavior... removing a 1px border makes <DIV> move about 20px

I have the following:

CSS

#pageBody
{
    height: 500px;
    padding:0;
    margin:0;
    /*border: 1px solid #00ff00;*/
}

#pageContent
{
    height:460px;
    margin-left:35px;
    margin-right:35px;
    margin-top:30px;
    margin-bottom:30px;
    padding:0px 0 0 0;
}

HTML

    <div id="pageBody"> 
    <div id="pageContent"> 
        <p> 
        blah blah blah
        </p> 
    </div> 
    </div> 

If I uncomment the border line in pageBody, everything fits sweetly... I had the border on to verify things were as expected. But removing the border, pageBody drops down the page about 20px, while pageContent does not appear to move at all.

Now this is not the real page, but a subset. If nothing's obvious I can attempt to generate a working minimal sample, but I thought there might be an easy quick answer first.

I see the same exact problem in Chrome and IE8, suggesting it's me not the browser. Any tips where to look? I wondered maybe the 1px border was some tipping point making the contents of a div just too big, but changing #pageContent height to e.g 400 makes no difference, other than clipping the bottom off that div.

like image 813
Mr. Boy Avatar asked May 28 '10 15:05

Mr. Boy


2 Answers

Appearently, when you add a border or a margin to the pageBody, the top of pageContent gets calculated as pageBody.border + pageBody.margin + pageContent.margin-top. Else it seems to ignore the pageContent.margin-top.

This is a typical case of margin collapsing

like image 197
Konerak Avatar answered Oct 11 '22 19:10

Konerak


Margins are collapsing.
(Visible with giving #pageBody red background and #pageContent blue background.)

That is: since both are block elements and margins are touching, they collapse together and the bigger one stays in effect.
If there is any border or padding between both margins, they aren't adjoining and thus don't collapse.

It's expected behaviour: http://www.w3.org/TR/CSS2/box.html#collapsing-margins

like image 26
ANeves Avatar answered Oct 11 '22 17:10

ANeves