Child margin adding margin to parent

2020-04-16 17:17发布

问题:

how if i have the following code : HTML :

<section class="home">
</section>
<section class="main">
    <h1>Hello</h1>

</section>

CSS code :

html,body{
    height: 100%;
    width: 100%;
}
.home{
    background: #000;
    height: 100%;
}
.main{
    height: 100%;
    background: pink;
}

Why the white space or rather margin between the 2 sections ?? the problem seems to be the h1 tag . if i do :

h1{
    margin: 0;
}

Bham ! problem solved .

I have two issues with this .

1st the minor problem , now this style might be applied by the browser , i ca correct this with a reset no issues . but this is still a problem nevertheless .

My 2nd problem , AND THE big problem , now suppose the browser or even i explicitly specify that the margin-top of the h1 should be say 20-30px the margin should be from side the .main section WHY IS THE MARGIN APPLIED TO h1 WHICH IS INSIDE .main ACTING AS A MARGIN BETWEEN .main and .home ? What is the cause of this unique problem ??

I have read about margin-collapsing:

Mozilla

css tricks

But this seems to be more like CHILD-MARGIN-ADDING-MARGIN-TO-PARENT .

Jsfiddle of issue

Thanks .

Alexander.

回答1:

http://jsfiddle.net/naeemshaikh27/qbaucv3j/1/

  .main{
        overflow: hidden; 
        height: 100%;
        background: pink;
    }

This is normal behaviour (among browser implementations at least). Margin does not affect the child's position in relation to its parent, unless the parent has padding, in which case most browsers will then add the child's margin to the parent's padding.

source https://stackoverflow.com/a/1939980/3556874



回答2:

Expected behavior in browsers is all too often unexpected .

What i really wanted to achieve by asking this question was not just get a solution to the problem but also actually know whats causing the problem .

which i eventually found in a thread not the same but similar and let me quote the part , that would solve the mystery :

The margins of the parent div and the h1 combine to form a single margin", even though they are nested, because they have adjoining margins with no padding or border between them.

and now coming to the solution well for me ,

overflow:hidden on the parent div worked just fine .

the same solution of course is high lighted by naeem in a earlier answer .

So heres the code : HTML :-

<section class="home"></section>
<section class="main">
        <h1>Hello</h1>

</section>

CSS:

html,body{
        height: 100%;
        width: 100%;
    }
    .home{
        background: #000;
        height: 100%;
    }
    .main{
        overflow: hidden; 
        height: 100%;
        background: pink;
    }

Here is the fiddle



标签: html css margin