4

I have the following:

<div>
    <p>some content</p>
</div>

or:

<div>
    some content
</div>

Without the:

<p>some content</p> 

...the div's positioning is different. It appears as though block content INSIDE the div is affecting the div's outer (top) margin. So is the div pushed down? I would think that content inside the div, like a block would not affect the containing block's margin. Why is the margin of the div affected by the content inside of it?

T.Rob
  • 31,522
  • 9
  • 59
  • 103
toddm
  • 55
  • 1
  • 3
  • 6

2 Answers2

13

You're talking about collapsing margins.

See: http://jsfiddle.net/thirtydot/vgJxX/

You can "fix it" by adding to the parent element:

  • A border.
  • Some padding.
  • position: absolute.
  • float: left.

HTML:

<div>
    <p>I'm doing the "broken" thing you hate.</p>
</div>

<div id="d2">
    <p>I'm not!</p>
</div>

<div id="d3">
    <p>Neither am I!</p>
</div>

<div id="d4">
    <p>Me neither!</p>
</div>

CSS:

div {
    background: #ccc
}
p {
    margin: 20px 0
}

#d2 {
    border: 1px solid red
}

#d3 {
    padding: 1px
}

#d4 {
    position: absolute;
    bottom: 0;
    width: 100%
}
thirtydot
  • 224,678
  • 48
  • 389
  • 349
3

Because of margin collapsing. Add a border or padding to your div.

robertc
  • 74,533
  • 18
  • 193
  • 177