Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - Margin collision between 2 DIVs

Tags:

html

css

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?

like image 863
giordanolima Avatar asked Jan 27 '14 18:01

giordanolima


People also ask

Do margins overlap CSS?

In CSS, adjacent margins can sometimes overlap. This is known as “margin collapse”, and it has a reputation for being quite dastardly. This is an interactive element! Instead of sitting 48px apart, their 24px margins merge together, occupying the same space!

How do you prevent margin collapse in CSS?

How to Avoid Margin Collapse. First, remember that margins should preferably be used to increase the distance between sibling elements, not to create spacing between a child and a parent. If you need to increase space within the Flow layout, reach first for padding if possible.

What causes container collapse CSS?

This happens because elements with float property are removed from the document flow so the sizes stay unknown for the parent element (as nothing is contained in it) so it is set to 0 .


Video Answer


1 Answers

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.

like image 200
Josh Crozier Avatar answered Sep 28 '22 19:09

Josh Crozier