Strange margin issue with a display: inline
Heres the fiddle
When I set #two
to inline-block it subtracts the 16 px of top/bottom margin from the <p>
and adds it to the divs content box height so it becomes 52px instead of 20px .. why is this the case?
What you're seeing is one of the stranger cases of margin collapsing.
If the parent and children are block elements and there's nothing (padding, a border, etc.) separating their vertical margins, then those margins will collapse. Collapsed margins are when two neighboring margins aren't added (as you might expect), but instead the larger of the two is displayed. In the parent-child case, the collapsed margin ends up outside the parent. You can read more details under the section Parent and first/last child in the above link.
Setting the parent to inline-block
, or float:left;
ing it or a number of other things (refer to the link for a more complete list) will stop the margins from collapsing. This leads to the behavior we're used to: the child's margin will appear inside the parent, adding to its total height, and the parent's margin will also be displayed.
To elaborate, and expand on the existing answers..
This behavior is known as collapsing margins.
8.3.1 Collapsing margins
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 .
To work around this, you need to establish a new block formatting context:
9.4.1 Block formatting contexts
Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
In a block formatting context, boxes are laid out one after the other, vertically, beginning at the top of a containing block. The vertical distance between two sibling boxes is determined by the 'margin' properties. Vertical margins between adjacent block-level boxes in a block formatting context collapse.
Therefore a few different ways to establish a new block formatting would be to..
Change the overflow
property of the parent element to something other than the default value, visible
- (updated example)
Change the display
of the element to inline-block
- (updated example)
Float the element - (updated example)
This has already been answered and accepted, still I'd like to point out that clearfixing it would have prevented margin collapse thus normalizing its behaviour
I'd add:
.two:before,
.two:after {
content: " ";
display: table;
}
.two:after {
clear: both;
}
See this fiddle . Here's the Nicholas Gallagher clearfix I've used.
链接地址: http://www.djcxy.com/p/89238.html上一篇: 如何删除表中的行和列之间的不需要的空间?
下一篇: 显示器奇怪的保证金问题:内联