Skip to content Skip to sidebar Skip to footer

Simple Html / Css Box Model Confusion

Using this really simple html / css (http://jsfiddle.net/XXzTj/)
hello

Solution 1:

try this --

<divstyle="background-color:red;height:auto;overflow:hidden;"><divstyle="margin:12px; background:blue;">hello</div></div>

http://jsfiddle.net/XXzTj/1/

Solution 2:

The child div is forcing the parent div to be rendered offset from its surroundings because you are using the margin property. Since the parent div has no content the browser has no reason to apply styling above or below the child div.

In order to honour the margin properties of the child div, however, which does have content, the parent div is rendered with its background either side of the content.

To have the browser render it in the way I imagine you expect, you would need to apply the padding style. Again, that's because the parent div has no content. Padding forces its styles to be rendered within the area because padding essentially acts like space that content would fill up.

Solution 3:

It's collapsing margins in action. Either use padding for parent element instead of margin for child one, or create new context by setting position: relative, overflow: auto/scroll/hidden, or add generated content (:before and :after pseudoelements) with display: block to parent element to prevent margin collapsing.

Solution 4:

Not too sure why that isnt working to be honest but this does work:

<divstyle="background-color:red; padding:12px;"><divstyle="background:blue;">hello</div></div>

Post a Comment for "Simple Html / Css Box Model Confusion"