Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my div's margin affected by content/blocks INSIDE of it?

Tags:

html

css

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?

like image 281
toddm Avatar asked Dec 05 '22 23:12

toddm


2 Answers

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%
}
like image 98
thirtydot Avatar answered Jan 03 '23 04:01

thirtydot


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

like image 30
robertc Avatar answered Jan 03 '23 03:01

robertc