嵌套div在框模型外应用边距

时间:2014-09-10 14:56:00

标签: html css html5 css3

我在<figure>嵌套<header>时,在添加保证金时遇到问题。

当我应用margin-top:10px时,它会应用于整个身体,而不是<header>标签内部。如果有帮助的话,我也在使用reset.css

这是为了在大学里完成一项作业,而且无法获得辅导老师的答案。

代码:

<html>
   <body>
   <header>
      <figure></figure>
   </header>
   </body>
</html>

CSS:

    body {
          backround-color: #f2f2f2;
          margin:0px;
          padding:0px;
    }
    header {
           display: block;
           position: static;
           max-width: 980px;
           height: 100px;
           background: #1e1e1e;
           margin:0px auto 0px auto;
    }
    header figure {
           margin-top:10px; /** when this margin top is added it creates a margin on the full page instead of inside the header**/
           margin-left:10px;
           max-width:200px;
           height:80px;
           background:red;
    }

2 个答案:

答案 0 :(得分:1)

您所看到的内容称为collapsing margins。将overflow:auto添加到标题中即可获得您之后的行为:

header {
    display: block;
    position: static;
    max-width: 980px;
    height: 100px;
    background: #1e1e1e;
    margin:0px auto 0px auto;
    overflow:auto;
}

<强> jsFiddle example

答案 1 :(得分:0)

padding添加到header。使用box-sizing:border-box也可以防止填充向外延伸:

header {
   display: block;
   position: static;
   max-width: 980px;
   height: 100px;
   background: #1e1e1e;
   margin:0px auto;
   padding: 10px 0 0 10px;
   -moz-box-sizing: border-box;
   -webkit-box-sizing: border-box;
   box-sizing: border-box;
}

JSFIDDLE