html – div内h1元素的边距

我有一个div容器,里面有一个h1元素:
<div id="header">
 <h1>Enlighten Designs</h1>
</div>

我已经在header元素中应用了margin-top,margin-left和margin-right.
但是,margin-top没有应用于包含div的头元素框wrt.
而是将上边距应用于包含div.
标题的左右边距将应用于包含div的标题元素框.

div和header的样式规则如下:

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

这种行为的原因是什么?

解决方法

你的’问题’是CSS中的边距会崩溃到另一个上面.

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

In simple terms,this deFinition indicates that when the vertical
margins of two elements are touching,only the margin of the element
with the largest margin value will be honored,while the margin of the
element with the smaller margin value will be collapsed to zero.

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

The top margin of an in-flow block element collapses with its first in-flow block-level child’s top margin if the element has no top border,no top padding,and the child has no clearance.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些