开发者

Can't figure out why background-color is including the margins!

开发者 https://www.devze.com 2023-02-18 03:29 出处:网络
Here is the code: <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">

Here is the code:

<!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>

According to the W3C page, background-color should only 'color' the content, padding, and border area; not the margins. Yet although there is a 20px margin between the red box and blue box text, it seems the background color of the blue box is including the t开发者_如何学JAVAop margin for some reason. I understand the concept of collapsing margins but it doesn't seem to make sense here.

Can anybody figure out what's going on?


The reason the bottom margin is being ignored on the id "redbox" is because it is floated left. If you remove the float the you will see the margin is respected.

If you did require "redbox" to be floated, then you could specify "clear:both" on "bluebox" to get the margins to be respected.

Generally anything that is floated needs to be cleared afterwards.


I think you need "overflow: hidden" on #redbox and #bluebox.


It's because #redbox is floated. Remove the float: left to see what you expect.


I figured it out.

If you set a border around the blue box, you will realise that the blue box is actually BEHIND the red box, presumably because the red box is floating and therefore out of the normal flow.

The solution is to use the overflow: auto declaration.

0

精彩评论

暂无评论...
验证码 换一张
取 消