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

Issue

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.

Solution

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.

Answered By – Quentin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published