微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/html/231605.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐