maxp
maxp

Reputation: 25151

Simple HTML / CSS box model confusion

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

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

The margin is spaced 12px all round correctly, but I was expecting the red background of the parent element to be shown in the top and bottom 12px spaces, instead its just 'blank space'.

Am I going mad or have I done something wrong?

Upvotes: 0

Views: 545

Answers (4)

Marat Tanalin
Marat Tanalin

Reputation: 14123

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.

Upvotes: 1

deed02392
deed02392

Reputation: 5022

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.

Upvotes: 1

Undefined
Undefined

Reputation: 11431

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

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

Upvotes: 0

Vivek Chandra
Vivek Chandra

Reputation: 4358

try this --

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

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

Upvotes: 1

Related Questions