Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
818 views
in Technique[技术] by (71.8m points)

css - Vertical margins disappear when parent is set to overflow:visible

Why do vertical margins disappear when the parent is set to overflow:visible? If it's set to overflow:hidden margins are visible again. It seems counterintuitive.

I think I understand how overflow is supposed to work when content of an element can't fit into it, but I don't understand what is happening with the margins.

Here's an example: ( http://jsfiddle.net/VrVc7/ )

#outer {
    background-color:#EEE;
    overflow:hidden;
}

#inner {
    margin: 30px;
    padding: 5px;
    background-color:#ABE;
}

<div id="outer">
    <div id="inner">abc</div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's called collapsing margin. As per W3c

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.

How to prevent from collapsing margin.

  1. Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
  2. Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
  3. Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).
  4. Margins of inline-block boxes do not collapse (not even with their in-flow children).
  5. The bottom margin of an in-flow block-level element always collapses with the top margin of its next in-flow block-level sibling, unless that sibling has clearance.
  6. 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.
  7. The bottom margin of an in-flow block box with a 'height' of 'auto' and a 'min-height' of zero collapses with its last in-flow block-level child's bottom margin if the box has no bottom padding and no bottom border and the child's bottom margin does not collapse with a top margin that has clearance.
  8. A box's own margins collapse if the 'min-height' property is zero, and it has neither top or bottom borders nor top or bottom padding, and it has a 'height' of either 0 or 'auto', and it does not contain a line box, and all of its in-flow children's margins (if any) collapse.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...