div内h1元素的余量

时间:2014-01-05 15:44:07

标签: html css css3 margins

我有一个div容器,里面有一个h1元素:

<div id="header">
 <h1>Enlighten Designs</h1>
</div>

我在header元素中应用了margin-top,margin-left和margin-right。 但是,margin-top不会应用于包含div的标题元素框。 而是将上边距应用于包含div。 标题的左右边距将应用于包含div的标题元素框。

div和标题的样式规则如下:

#header {
    background: blue;
    height: 150px;
}
h1{
    background: orange;
    margin-top:30px;
    margin-left: 10px;
    margin-right: 10px;
}

这种行为的原因是什么?

3 个答案:

答案 0 :(得分:6)

你的“问题”是CSS中的边距将会崩溃。

Read this awesome article explaining the concept,管理摘要:

  

简单来说,这个定义表明当垂直时   两个元素的边距是触及的,只有元素的边缘   具有最大保证金价值将被兑现,而保证金   边际值较小的元素将折叠为零。

在您的情况下,请专门阅读“在父元素和子元素之间折叠边距”部分几页。在您的情况下,following CSS 2.1 rule适用:

  

流入块元素的上边距与其第一个边缘折叠   如果元素没有顶部,则流入块级子级的上边距   边界,没有顶部填充,孩子没有间隙。

答案 1 :(得分:5)

嗯,解决方法是在标题元素中添加overflow: hidden;属性 Here JsFiddle.

答案 2 :(得分:-1)

#header {
    background: blue;
    height: 150px;
    position:absolute;
}
h1{
    background: orange;
    margin-top:30px;
    margin-left: 10px;
    margin-right: 10px;
    position:relative;
}