nonopolarity
nonopolarity

Reputation: 151036

For CSS, vertical margin collapses, but why floated divs don't collapse vertical margins?

For CSS, we know that vertical margin collapses, such as in example:

http://jsfiddle.net/rbxL7/5/

(The vertical margin between the divs are only 30px.)

But what about floated divs? Why do the vertical margins not collapse?

example: http://jsfiddle.net/rbxL7/3/

(the horizontal and vertical margins between the divs both end up as 60px).

Upvotes: 1

Views: 1072

Answers (2)

ataddeini
ataddeini

Reputation: 4951

According to 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.

and...

Two margins are adjoining if and only if:

1) both belong to in-flow block-level boxes that participate in the same block formatting context

which leads to...

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.

Upvotes: 5

Petah
Petah

Reputation: 46040

You could try this:

.outer { width: 600px; border: 1px dashed blue; overflow: hidden }  /* overflow: hidden is to clear the float if any */
.inner { float: left; width: 200px; height: 200px; border: 1px dashed orange; margin: 30px 0 0 30px; }
.outer .inner:last-child { margin: 30px; }

(If you target browsers don't support last-child, then add a class to the last child)

See http://jsfiddle.net/rbxL7/6/

Upvotes: 1

Related Questions