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
553 views
in Technique[技术] by (71.8m points)

html - CSS - Margin collision between 2 DIVs

I have two DIV`s and i think I have a margin collision...

<div style="margin-bottom: 10px;">Example box</div>
<div style="margin-top: 10px;">Example box</div>

I have 10px between them, and I want 20px.. Any suggest?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As others have already said, this is known as collapsing margins:

8 Box model - 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.

In this case, they are sibling elements; therefore the following applies:

Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).

Floating one of the sibling elements would prevent the margins from collapsing:

EXAMPLE HERE

<div style="margin-bottom: 10px;">These are NOT</div>
<div style="margin-top: 10px; float:left;">collapsing</div>

Margins of inline-block boxes do not collapse (not even with their in-flow children).

Making an element inline-block would also prevent the margins from collapsing:

EXAMPLE HERE

<div style="margin-bottom: 10px;">These are NOT</div>
<div style="margin-top: 10px; display:inline-block;">collapsing</div>

Assuming the elements weren't siblings, you could add overflow:hidden to the parent element, as the following would then apply:

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.


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

...