h1元素上的边距 [英] margin on h1 element inside a div

查看:647
本文介绍了h1元素上的边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div容器,其中有一个h1元素:

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

我已经对页眉元素应用了页边距,页边距左边和页边距。
然而,margin-top不应用于包含div的标题元素框wrt。
而不是顶边距应用于包含div。
标题的左右边距将应用于包含div的标题元素框。



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

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

这种行为的原因是什么?


http://reference.sitepoint.com/css/collapsingmargins =nofollow>阅读解释概念的这篇真棒文章,管理摘要:


简单来说,这个定义表示当两个元素的垂直
边界接触时,只有具有最大边际值的元素
的边界将被遵守,而


在您的情况下,具体读取部分在父元素和子元素之间折叠边距下几页。在您的情况下,遵循CSS 2.1规则适用: p>


流内块元素的顶部边缘与其第一个
流入块级子项的顶部边缘折叠,如果元素没有顶部的
边框,没有顶部填充,并且孩子没有清除。



I have a div container which has a h1 element within it:

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

I have applied a margin-top,a margin-left and a margin-right to the header element. However the margin-top is not being applied to the header element box wrt to the containing div. Instead the top margin is being applied to the containing div. The left and right margins of the header are being applied to the header element box wrt the containing div.

The style rules for the div and header are as follows:

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

What is the reason for this behavior?

解决方案

Your 'problem' is that margins in CSS will collapse onto eachother.

Read this awesome article explaining the concept, management summary:

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.

In your case, specifically read the section "Collapsing Margins Between Parent and Child Elements" a few pages down. In your case, the following CSS 2.1 rule applies:

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.

这篇关于h1元素上的边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆