Margin-top of DIV daughter pushes her and DIV father together

0

I'm wanting #div1 to move away from #fisrt and not to #second together, but it's not working with margin-top: 5px; on #div1; . That is, between joining #first and #second I want #div1 to move away 5px without leading to #second .

Follow the code:

 * {
     margin: 0 auto;
     padding: 0 0 0 0;
 }
    
 #first {
     background: blue;
     width: 100%;
     height: 34px;
 }
            
 #second {
     background-color: gray;
     width: 100%;
     height: 100%;
     background: red;
 }
    
 #div1 {
     background: green;
     width: 200px;
     height: 30px;
     margin-top: 10px;
 }
<div id="first">
</div>
<div id="second">
    <div id="div1"> Destaques </div>
</div>
    
asked by anonymous 13.03.2017 / 21:36

3 answers

3

I think it's due to the box-model: "margin-top" and "margin-bottom" overlapping, why? / a>

If you just add a pixel in the #second it should resolve, I also recommend not adding margin: 0 auto to the global selector.

In case you add padding-top: 1px; and instead of margin-top: 10px; , change by margin-top: 9px; to compensate 1px

Extra: Put margin: 0 auto; only in #div1 , since it is the only one that needs to be aligned in the center:

* {
     margin: 0;
     padding: 0;
}

#first {
     background: blue;
     width: 100%;
     height: 34px;
}
       
#second {
     background-color: gray;
     width: 100%;
     height: 100%;
     background: red;
     padding-top: 1px;
}

#div1 {
     background: green;
     width: 200px;
     height: 30px;
     margin: 0 auto;
     margin-top: 9px;
}
<div id="first"></div>

<div id="second">
    <div id="div1"> Destaques </div>
</div>
    
13.03.2017 / 22:13
1

You need to set a position for the #second div. In case.. Just put float: left in the #second div.

 * {
     margin: 0 auto;
     padding: 0 0 0 0;
 }

 #first {
     background: blue;
     width: 100%;
     height: 34px;
 }

 #second {
     background-color: gray;
     width: 100%;
     height: 100%;
     background: red;
     float: left;
 }

 #div1 {
     background: green;
     width: 200px;
     height: 30px;
     margin-top: 10px;
 }
<div id="first">
</div>
<div id="second">
    <div id="div1"> Destaques </div>
</div>
    
14.03.2017 / 00:30
0

I made a small example, which does not move the divs first and second , only the child div with the position: absolute property. I imagine that's what I was looking for.

 * {
     margin: 0 auto;
     padding: 0;
 }

#first, #second {
     width: 100%;
     height: 34px;
     position: relative;
}
 #first {
     background: blue;
 }
            
 #second {
     background: red;
 }
    
 #div1 {
     position: absolute;
     top: 15px;
     left: calc(50% - 100px);
     background: green;
     width: 200px;
     height: 30px;
 }
<div id="first"></div>
<div id="second">
  <div id="div1"> Destaques </div>
</div>
    
13.03.2017 / 23:32