Search code examples
csshtmlmargin

changing margin-top affects others


When I increase or decrease margin-top of #nav it affects #header, but when increasing margin-top of #header it doesn't affect #nav.

How to correct this to when I change whether nav or header it shouldnt affect other?

body {
  width: 960px;
  margin: auto;
  color: #000000;
  background-color: #fff;
}

h1 {
  margin: 0;
  padding: 5px;
}

#header {
  float: left;
  color: #000000;
  font-size: 20px;
  margin-top: 10px;
}

#header h1 {
  float: left;
}

#nav {
  width: 900px;
  ;
  height: 20px;
  position: relative;
  margin-top: 34px;
}

#nav li {
  display: inline;
  float: left;
}
<div id="header">
  <h1>rrrr</h1>

</div>

<div id="nav">
  <ul>
    <li><a href="#">sss</a></li>
    <li><a href="#">www</a></li>
    <li><a href="#">fff</a></li>
    <li><a href="#">ttt</a></li>
  </ul>
</div>


Solution

  • You are facing a margin-collapsing issue. Since you made the header to be a float element, the #nav become the first in-flow element thus its margin will collapse with body margin.

    top margin of a box and top margin of its first in-flow child

    So when you increase the margin of the nav you increase the collapsed margin which is the margin of the body and you push all the content down including the #header.

    To fix this you need to avoid the margin collapsing by adding (for example) a padding-top to the body.

    body {
      width: 960px;
      margin: auto;
      color: #000000;
      background-color: #fff;
      padding-top: 1px;
    }
    
    h1 {
      margin: 0;
      padding: 5px;
    }
    
    #header {
      float: left;
      color: #000000;
      font-size: 20px;
      margin-top: 10px;
    }
    
    #header h1 {
      float: left;
    }
    
    #nav {
      width: 900px;
      ;
      height: 20px;
      position: relative;
      animation: ani1 2s;
      margin-top: 34px;
    }
    
    #nav li {
      display: inline;
      float: left;
    }
    <div id="header">
      <h1>rrrr</h1>
    </div>
    <div id="nav">
      <ul>
        <li><a href="#">sss</a></li>
        <li><a href="#">www</a></li>
        <li><a href="#">fff</a></li>
        <li><a href="#">ttt</a></li>
      </ul>
    </div>