日期:2014-05-17  浏览次数:20628 次

问一个基础的CSS问题……

<html>
  <head>
   <style>
     .container{ background: #aabbcc; width: 1000px; height: 1500px; margin: auto; }
     .top{ background: #ccc; width: 900px; height: 150px; margin: auto; }
     .nav{ background: #aaa; width: 900px; height: 100px; margin: auto; }
     .main{ background: #bbb; width: 900px; height: 1000px; margin: auto; }
     .footer{ background: #ddd; width: 900px; height: 150px; margin: auto; }
   </style>
  </head>
  <body>
   <div class="container">
     <div class="top"></div>
     <div class="nav"></div>
     <div class="main"></div>
     <div class="footer"></div>
   </div>
  </body>
</html>


我发现类似.top{ margin-top:100px }或者.footer{ margin-bottom:100px }的样式都是没效果的。
而.nav{ margin:100px auto }和.main{ margin:100px auto }是有效果的……
那么想问一下margin是不是同级元素的间距?
我需要实现top离container的顶部100px, footer贴紧container的底部。我应该怎样做?
不会是需要事先计算好吧……
------解决方案--------------------
用padding呢?我是菜鸟,这是我的想法。margin有时候会重合,你看W3C教程有说明的。
<html>
  <head>
      <style>
        .container{ background: #aabbcc; width: 1000px; height: 1500px; margin:0 auto; padding-top: 100px;padding-bottom: 100px}
        .top{ background: #ccc; width: 900px; height: 150px; margin:0 auto; }
        .nav{ background: #aaa; width: 900px; height: 100px; margin: 0 auto; }
        .main{ background: #bbb; width: 900px; height: 1000px; margin:0 auto; }
        .footer{ background: #ddd; width: 900px; height: 150px; margin:0 auto; }
      </style>
  </head>
  <body>
      <div class="container">
        <div class="top"></div>
        <div class="nav"></div>
        <div class="main"></div>
        <div class="footer"></div>
      </div>
  </body>
</html>

------解决方案--------------------
直接这样不行吗.container{ background: #aabbcc; width: 1000px; height: 1500px; margin: auto; padding:100px 0;}
------解决方案--------------------
添加 overflow:hidden;  有高度跟宽度定义过的 块
------解决方案--------------------