问题
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?
回答1:
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.
回答2:
Margin-Top and Margin-Bottom is not used by elements with display:inline; See: Margin top in inline element
回答3:
Top and Bottom margins in inline elements are not important. In inline elements, each element represents a word in a text.
来源:https://stackoverflow.com/questions/14358862/basic-html-css-margin-display-behaviour