Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parent div inheriting child divs margin

Tags:

html

css

It doesnt happen all the time but, every once in a while, The parent div inherits the child divs properties and throws my layouts positioning out of whack.

for example, this is the html(pseudo):

<div 1>
   <div 2>
      content here
   </div>

</div><!-- div one end -->

the Css (pseudo):

#1{ margin top:0; }
#2 {margin top:10 }

its supposed to look like this: div 1 the parent and div 2 the child

div 1parent

-----------------------------------------
this is address bar (top of win)
-----------------------------------------
----------------
|  ----------  |
| | div2Child  |
| ------------ |
|--------------| 

assume that there isnt a gap from div 1 to addy window.

now, for some odd reason, using the same code above, when i preview, i get this:

-----------------------------------------
this is address bar (top of win)
-----------------------------------------

gap here.

----------------
|  ----------  |
| |   div2     |
| ------------ |
|--------------| 

no matter what i do i still get that gap. When i take it to firebug and test on the Divs, div2 clearly shows that the margin is affecting the parents positioning.

..i was going to put up an example but...well heres the actual code so you can see...(simple as can be)

HTML:

<div id="one">
    <div id="two">content here on 2</div>
</div>

the CSS: 

    #one{
        width:1000px;
        height:300px;
        background:#09F;
        margin-top:0px !important;
padding:0px;


    }

    #two{
        width:500px;
        height:100px;
        background:red;
        margin-top:20px;
padding:0px;
    }

and i still get the gap i showed above in my diagram. What drives me crazy is, like most of us, weve done this layout millions of times....i can pull up DOZENS of works that use this same method and no problems...i have my Cssreset that i always use. have the !important, no random <br/> or <p> , 0 padding... matter of fact to make SURE, i created a dummy page with nothing but the 2 divs and their css and still........

Any thoughts as to why this happens? cause right now im looking at my last site create and this dummy html i just made to test and on every browser, i get that stupid gap.

like image 234
somdow Avatar asked Apr 04 '12 18:04

somdow


2 Answers

What you're observing is margin-collapse. It can happen in scenarios that aren't always straightforward to understand, so I suggest referring to documentation.

like image 141
kinakuta Avatar answered Sep 28 '22 04:09

kinakuta


Why not use:

#one{
        width:1000px;
        height:300px;
        background:#09F;
        margin-top:0px !important;
        padding-top:20px;
    }
    #two{
        width:500px;
        height:100px;
        background:red;
        margin-top:0px;
        padding:0px;
    }​

? just wondering

like image 26
Isaac Fife Avatar answered Sep 28 '22 03:09

Isaac Fife