css - 无法弄清楚为什么背景颜色包括边距!

标签 css margin background-color

代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>

<head>
    <title></title>

    <style type="text/css">

    * {border: 0px; padding: 0px;}

    #greenbox
    {
        margin: 20px;
        border: 5px solid green;
    }   

    #redbox
    {
        background-color: red;
        margin: 20px;
        float:left;
        width:50%;
    }

    #bluebox
    {
        background-color: blue;
        margin: 20px;
        width: 50%;
    }


    </style>
</head>
<body>

    <div id="greenbox">

        <div id="redbox"> red box </div>

        <div id="bluebox"> blue box </div>

    </div>
</body>
</html>

根据 W3C 页面,background-color 应该只为内容、填充和边框区域“着色”;不是边距。然而,尽管红框和蓝框文本之间有 20px 边距,但由于某种原因,蓝框的背景颜色似乎包括了上边距。我理解折叠边距的概念,但它在这里似乎没有意义。

有人能弄清楚发生了什么吗?

最佳答案

id“redbox”上的底部边距被忽略的原因是因为它向左浮动。如果您移除 float ,您将看到边距得到尊重。

如果您确实需要 float “redbox”,那么您可以在“bluebox”上指定“clear:both”以使边距得到尊重。

通常任何 float 的东西都需要在之后清除。

关于css - 无法弄清楚为什么背景颜色包括边距!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5368530/

相关文章:

css - 不考虑背景颜色 rgba 不透明度的标签

html - anchor 背景颜色变化

javascript - 如何使 ReactJS 中的 onChange 文本响应

jquery - 我如何使这个 jQuery 动画在第二次单击时反转/切换/向后播放?

html - 右边距在 block 内不起作用

css - 为什么我访问过的链接没有背景颜色?

javascript - 如何水平对齐推特按钮和普通按钮?

javascript - 使用getuikit框架扩展第二列

internet-explorer - CSS 问题 : Combination of "text-align: center" and "min-width" not working in IE 7/IE 8 compat mode

html - 如何使 HTML 列表环绕 float 内容