SteveX
SteveX

Reputation: 67

Why does my margins collapse even though I have borders around everything?

Here is the code:

<html>

    <head>
        <title></title>

        <style type="text/css">

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

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

        }   

        #redbox
        {
            margin: 20px;
            border: 5px solid red;
        }

        #bluebox
        {
            border: 5px solid blue; 
            margin-left: 20px;
            margin-right: 20px;
            margin-bottom: 20px;
                        margin-top: 20px; /*COLLAPSES - why??*/
        }

        </style>
    </head>
    <body>

        <div id="greenbox">

            <div id="redbox">

                red box
            </div>

            <div id="bluebox">

                    bluebox

            </div>

        </div>



    </body>
</html>

Basically, it's a green box, which contains a red box and a blue box inside it.

Why isn't the vertical space between the red box and blue box 40px?

I understand that the bottom-margin of the red box and the top margin of the blue box have 'collapsed', but it was my understanding that margins do not collapse if you have a border, or padding (I've tried both - still the same result.

Upvotes: 0

Views: 248

Answers (2)

Quentin
Quentin

Reputation: 943569

Margins do not collapse through borders. They do collapse through each other.

See this example:

<style>
body { background: black; }
.red { background: red; }
.blue { background: blue; }
.border { border: solid white 1px; }
div { margin: 20px; min-height: 30px; width: 50% }
</style>


<div class="red">
    <div class="blue">
    </div>
</div>

<div class="red border">
    <div class="blue border">
    </div>
</div>

When the border is present, the margin on the top of the blue div pushes the top of the blue div away from the top of the red div that it is inside. When the border is not present, the margin goes through the edge and collapses into the margin around the red div.

Your two margins are touching each other with no border between them — so they collapse.

Upvotes: 2

Martin Jespersen
Martin Jespersen

Reputation: 26183

Margins are outside border in the box model, thus the borders have nothing to do with margins that collapse.

You can read up on the box model here: http://www.w3.org/TR/CSS21/box.html

You can read up on collapsing margins here: http://www.w3.org/TR/CSS21/box.html#collapsing-margins

Upvotes: 2

Related Questions