Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't child vertical margins expand parent container?

Tags:

css

margin

I have come across a case where I need a child's margin to expand a parent container. I found that the space outside of the parent is allocated, but the parent itself is not expanded. I then found that by adding `overflow: hidden' to the parent I could fix this issue.

Can anyone shed any light on why this is the case?

UPDATE:

I have found that adding any padding or border value to the parent also fixes this.

Updated Example

like image 451
wilsonpage Avatar asked Jul 26 '12 11:07

wilsonpage


2 Answers

The answer to "why" is described well and succinctly here. There are certain properties that establish a "block formatting context". Namely:

Floats, absolutely [and fixed] 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.

It is this change of block formatting context that is the reason why such solutions as given above in the comments work for how margin (and in the case of a preceding float, padding of following inflow elements) operates.

like image 115
ScottS Avatar answered Sep 20 '22 11:09

ScottS


I think collapsing margins is the reason : http://www.w3.org/TR/CSS2/box.html#collapsing-margins

like image 27
Thierry Avatar answered Sep 20 '22 11:09

Thierry