基本HTML/CSS-边距和显示行为 [英] Basic HTML/CSS - margin & display behaviour

查看:105
本文介绍了基本HTML/CSS-边距和显示行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于HTML/CSS和某些元素的边距行为,我有一个基本问题.
为了阐明我的观点,我创建了这个小提琴: http://jsfiddle.net/5VA5h/

您知道,我对所有h1应用了某种重置"并添加了一些样式.
在第一个示例中,h1中的margin应用于框的外部,而在#c中将h1设置为display: inline;的框,则将其应用于框的内部.

为什么会这样?

解决方案

在您的第一个示例中,以<h1>作为块元素,顶部的

  • 未建立新块格式上下文且具有零个计算出的最小高度",零个或自动"个计算出的高度"且没有流入子项的框的上边距和下边距
  • 第二个示例,以<h1>作为内联元素,垂直边距不生效:

    'margin'速记属性设置所有四个边的边距,而其他margin属性仅设置它们各自的边.这些属性适用于所有元素,但是垂直边距不会对未替换的嵌入式元素产生任何影响.

    I have a basic question regarding HTML/CSS and the behaviour of margins from certain elements.
    To make my point clear, I created this fiddle: http://jsfiddle.net/5VA5h/

    You see, I applied some kind of "reset" and added some styles to all h1.
    In the first example, the margin from h1 is applied on the outside of the box, while in #c, where h1 is set display: inline;, it is applied inside the box.

    Why is this so?

    解决方案

    In your first example, with the <h1> as a block element, the top margin is collapsing (emphasis mine):

    In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

    ...and later:

    Two margins are adjoining if and only if:

    • both belong to in-flow block-level boxes that participate in the same block formatting context
    • no line boxes, no clearance, no padding and no border separate them (Note that certain zero-height line boxes (see 9.4.2) are ignored for this purpose.)
    • both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
      • top margin of a box and top margin of its first in-flow child
      • bottom margin of box and top margin of its next in-flow following sibling
      • bottom margin of a last in-flow child and bottom margin of its parent if the parent has 'auto' computed height
      • top and bottom margins of a box that does not establish a new block formatting context and that has zero computed 'min-height', zero or 'auto' computed 'height', and no in-flow children

    The second example, with the <h1> as an inline element, the vertical margins do not take effect:

    The 'margin' shorthand property sets the margin for all four sides while the other margin properties only set their respective side. These properties apply to all elements, but vertical margins will not have any effect on non-replaced inline elements.

    这篇关于基本HTML/CSS-边距和显示行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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