【问题标题】:Why are my div's margin affected by content/blocks INSIDE of it?为什么我的 div 的边距会受到其中的内容/块的影响?
【发布时间】:2011-07-12 02:36:03
【问题描述】:

我有以下:

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

或:

<div>
    some content
</div>

没有:

<p>some content</p> 

...div的定位不同。似乎 div 内部的块内容正在影响 div 的外部(顶部)边距。那么div被推倒了吗?我认为 div 内的内容(如块)不会影响包含块的边距。为什么div的margin会受里面的内容影响?

【问题讨论】:

    标签: html css


    【解决方案1】:

    你说的是collapsing margins

    见: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>
    

    CSS:

    div {
        background: #ccc
    }
    p {
        margin: 20px 0
    }
    
    #d2 {
        border: 1px solid red
    }
    
    #d3 {
        padding: 1px
    }
    
    #d4 {
        position: absolute;
        bottom: 0;
        width: 100%
    }
    

    【讨论】:

    【解决方案2】:

    因为margin collapsing。为您的 div 添加边框或填充。

    【讨论】:

      猜你喜欢
      • 2013-06-12
      • 2017-09-29
      • 2019-10-24
      • 2011-12-20
      • 1970-01-01
      • 2021-01-23
      • 2013-06-24
      • 2011-08-07
      相关资源
      最近更新 更多