【问题标题】:margin-top:percentage; not bound to parent height?边距顶部:百分比;不受父母身高限制?
【发布时间】:2014-01-07 02:16:02
【问题描述】:

我有一个 <div>,它是 100px 高(用于演示目的)。
<div> 里面是另一个60% 高的margin-top 20%
我希望结果是 60px<div>margin-top20px

不幸的是,事实并非如此,我无法弄清楚这一点。

这是 CSS:

html, body {
     min-height:100%;
}
div#one {
     height:100px;
}
div#two {
    background:red;
    height:60%;
    margin-top:20%;
    margin-bottom:0;
    width:100%;
}

还有 HTML:

<html>
    <body>
        <div id="one">
            <div id="two">
                &nbsp;
            </div>
        </div>
    </body>
</html>

这是一个jsFiddle 可以玩。

【问题讨论】:

    标签: css height margin


    【解决方案1】:
    html, body {
        min-height: 100px;
    }
    
    div#one {
        height: 100px;
    }
    
    div#two {
        background: red;
        height: 60px;
        margin-top: 20px;
        margin-bottom: 0;
        width: 100%;
    }
    

    http://jsfiddle.net/HpaQp/1/

    【讨论】:

    • 100px 只是示例,我需要使用百分比。
    【解决方案2】:

    使用relative 位置尝试this fiddle

    div#one {
        background-color:green;
        height:100px;
        width: 100%;
    }
    
    div#two {
        float: left;
        position: realtive;
        background:red;
        height:60%;
        width: 100%;
        margin-top: 2.5%;
    }
    

    【讨论】:

    • 在 Chrome 和 Safari 中试过,没有回答问题。
    • webkit-flex; 仍然没有回答问题。 div#two 应该有一个 20% 上边距。
    • 使用 position: relativefloat: left 更新了 Fiddle。看看吧。
    【解决方案3】:

    http://jsfiddle.net/HpaQp/5/


    html, body {
        margin: 0px;
        padding: 0px;
    }
    div#one {
        height: 100px;
        min-height: 100px;
        max-height: 100px;
    }
    

    【讨论】:

      【解决方案4】:

      如果您查看 http://www.w3.org/TR/CSS2/box.html#propdef-margin-top 的规格,您会注意到

      百分比:指包含块的宽度

      所以在你的情况下 20% 应用于 #two 意味着 #one 宽度的 20%

      【讨论】:

        【解决方案5】:

        margin/padding 属性的百分比值始终与包含块的宽度相关,即使在 margin-topmargin-bottom 的情况下 - 来自 2.1 Spec

        保证金

        &lt;percentage&gt;: 百分比是根据生成框的包含块的宽度计算的。 注意,'margin-top' 和 'margin-bottom' 也是如此。如果包含块的宽度取决于此元素,则结果布局在 CSS 2.1 中未定义。

        【讨论】:

          猜你喜欢
          • 2012-05-09
          • 2015-08-12
          • 1970-01-01
          • 2013-05-19
          • 2018-01-01
          • 1970-01-01
          • 2013-08-23
          • 2020-04-30
          • 2023-03-12
          相关资源
          最近更新 更多