Child margin adding margin to parent

后端 未结 2 779
别跟我提以往
别跟我提以往 2021-01-22 19:44

how if i have the following code : HTML :

Hello

相关标签:
2条回答
  • 2021-01-22 20:27

    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

    0 讨论(0)
  • 2021-01-22 20:36

    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

    0 讨论(0)
提交回复
热议问题