为什么我的div的余量会受到内容/块内容的影响?

tod*_*ddm 4 html css

我有以下内容:

<div>
    <p>some content</p>
</div>
Run Code Online (Sandbox Code Playgroud)

要么:

<div>
    some content
</div>
Run Code Online (Sandbox Code Playgroud)

没有:

<p>some content</p> 
Run Code Online (Sandbox Code Playgroud)

...... div的定位是不同的.似乎div中的块内容正在影响div的外(上)边距.div被推下来了吗?我认为div内的内容就像一个块一样不会影响包含块的边距.为什么div的边距受其内容的影响?

thi*_*dot 13

你在谈论崩溃利润.

请参阅:http://jsfiddle.net/thirtydot/vgJxX/

您可以通过添加到父元素来"修复它":

  • border.
  • 一些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>
Run Code Online (Sandbox Code Playgroud)

CSS:

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

#d2 {
    border: 1px solid red
}

#d3 {
    padding: 1px
}

#d4 {
    position: absolute;
    bottom: 0;
    width: 100%
}
Run Code Online (Sandbox Code Playgroud)