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


Here is the code:



        <style type="text/css">

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

            margin: 20px;
            border: 5px solid green;


            margin: 20px;
            border: 5px solid red;

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


        <div id="greenbox">

            <div id="redbox">

                red box

            <div id="bluebox">





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.


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

See this example:

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

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

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

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