【问题标题】:Why isn't 'margin-top' property working?为什么'margin-top'属性不起作用?
【发布时间】:2013-05-26 19:10:42
【问题描述】:

我知道“边距折叠”的概念。但是,为什么我在第一个框here 的顶部看不到 10 px 的边距。顶框(其 id 为“first”)上方应有 10px 的边距。如果这不是获得它的正确方法,那么它是什么?而且,为什么这不起作用。

CSS:

#Main{
background-color: gray;
position: relative;
width: 200px;
height: 300px;  
}


.box{
position:relative;
height: 60px;
width: 175px;
background: black;
margin: 10px 10px 10px 10px;
}

HTML:

<div id="Main"> 
    <div id="first" class="box"></div>
    <div id="second" class="box"></div>
    <div id="third" class="box"></div>
</div>

我知道一种方法是我们可以为父 div 提供 10px 的填充。但是为什么这东西不起作用呢?

【问题讨论】:

  • @BoltClock♦ 不,这不是我问题的答案。我没有为父元素提供任何边距。那么,它们怎么会崩溃呢?
  • 哦,我看错了。但同样的原则也适用,即使父元素的边距为零
  • @BoltClock♦ 怎么可能?如果没有为外部父 div 提供边距,边距将如何折叠?
  • 来自子元素。

标签: css margin


【解决方案1】:

代码中的margin: 10px 10px 10px 10px 也会移动“Main” 框。
如果您只想移动 ID 为 "first" 的框,请使用 position:relative; top: 10px;
jsfiddle demo

编辑:我不知道为什么会发生这种情况,但我猜这是因为 "Main" 框的display 默认为block
当您在 "Main" 框上使用 display: inline-block; 时,问题已得到解决。 (jsfiddle)

【讨论】:

  • 你能解释一下'margin: 10px 10px 10px 10px'是如何移动主框的吗?
【解决方案2】:

这就是浏览器交互代码的方式。它不会输出预期的结果,即孩子的顶部和外部父母之间的 10px 间隙。您可以将padding-top 添加到父级,或者您可以将overflow:auto; 分配给您的主div。

演示http://jsfiddle.net/kevinPHPkevin/2f4Kz/4/

#Main {
    background-color: gray;
    position: relative;
    width: 200px;
    height: 300px;
    overflow:auto;
}

另一种解决方法是在主 div 周围添加透明边框(停止边距折叠)

#Main {
        background-color: gray;
        position: relative;
        width: 200px;
        height: 300px;
        border: thin solid transparent;
    }

第三个最终选项(据我所知)是通过将padding-top: 1px; margin-top: -1px; 设置为父 div 来阻止边距折叠

#Main {
    background-color: gray;
    position: relative;
    width: 200px;
    height: 300px;
    padding-top: 1px;
    margin-top: -1px;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2022-12-26
    • 1970-01-01
    相关资源
    最近更新 更多