CSS最高保证金问题 [英] CSS Top-Margin Issue

查看:83
本文介绍了CSS最高保证金问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道为什么我基于下面的CSS在第一个div中没有​​获得最高利润吗?这在Mac OSX Lion上运行的Chrome,Safari和Firefox 4中具有相同的效果(在Snow Leopard中具有相同的效果).我希望第一项在内部div周围始终显示5px的边距(显然,底部除外),而不仅仅是左右.为什么不将保证金也不适用于顶部?即使我在CSS中指定margin-top:5px,也仍然无法如我所愿.

Does anyone know why I don't get a top-margin in the first div based on the CSS below? This renders the same in Chrome, Safari and Firefox 4 running on Mac OSX Lion (rendered the same in Snow Leopard). I would expect the first item to display with a 5px margin all the way around the inner div (except for the bottom obviously) and not just on the right and left. Why would the margin not also be applied to the top? Even if I specify margin-top:5px in the CSS it still doesn't render as I would expect.

<!DOCTYPE html>
<html>

    <head>
        <style>
        .outer{
            background-color:red;
            width:100px;
            height:100px;
            margin-bottom:20px;
        }

        .inner{
            background-color:white;
            margin:5px;
        }

        .shim{
            height:1px;
        }

        .outer2{
            background-color:red;
            width:100px;
            height:100px;
            margin-bottom:20px;
            padding:5px;
        }

        .inner2{
            background-color:white;
        }
        </style>
    </head>

    <body>

        <div class="outer">
            <div class="inner">
                Margin
            </div>
        </div>

        <div class="outer">
            <div class="shim"></div>
            <div class="inner">
                Margin+Shim
            </div>
        </div>

        <div class="outer2">
            <div class="inner2">
                Padding
            </div>
        </div>

    </body>

</html>

推荐答案

您遇到了一个常见的问题,称为崩溃边距".基本上,只要碰到垂直边距(即使一个元素在另一个元素内),边距就会崩溃.

You're running into a common problem called "collapsing margins." Basically, whenever vertical margins touch (even when one element is inside another element), the margins collapse.

在这种情况下,内部div上的margin属性会崩溃到外部div的margin-bottom: 20px;属性中.要解决此问题,请在包含的元素周围添加一些填充或边框.

In this case your margin property on the inner div is collapsing into the margin-bottom: 20px; property on your outer div. To fix this, add a little padding or a border around the containing element.

只需使用您的代码尝试一下,它就会起作用: http://jsfiddle.net/hWPyD/2/

Just tried this using your code and it works: http://jsfiddle.net/hWPyD/2/

有关利润下降的更多信息: http://www.w3.org/TR/CSS2/box.html #collapsing-margins

More info on collapsing margins: http://www.w3.org/TR/CSS2/box.html#collapsing-margins

这篇关于CSS最高保证金问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆