CSS – Preventing Margin Collapse

At times the top and bottom margins of block elements might collapse into a single margin. Here are easy CSS solutions to prevent the margins of your block elements from collapsing.

One of the strange quirks you might face when coding in css, is that sometimes you can’t add any white space (margin) to some elements. In other words, no matter how much you increase the values of margins no white space will be show up in the browser. it’s a frustrating.

For instance, if you have two boxes and each of them have been given 20px margin, since top margin of the second box is in contact with the bottom margin of the first box, the margins collapse and the element will have a total margin of 20px rather than 40px.css margin

Margin collapse might also occur when one block element is the child of another block element. Again, the top and bottom margins of the second element disappears and there’s only 20px margin around parent element.

css margin 2

There are a couple of methods to prevent css Margin Collapse problem.

1-   Add a border to the element

2-   Add 1px of padding

3-   change the position property. Margins of absolutely and relatively positioned boxes don’t collapse.

Now they look ok:

css margin 3css margin 4

4 comments

  1. Daniela - May 19, 2012 10:17 pm

    thanks for taking a time to help people with so great information, congratulations, your work is so dignifying.

    Reply
  2. site - May 30, 2012 6:56 pm

    This blog is extremely cool! How did you make it !

    Reply
  3. diryboy - April 23, 2014 4:52 pm

    Thank you for explaining that in pictures! That helps a lot!

    Reply
    • Faraz - April 24, 2014 7:05 am

      You’re welcome.

      Reply

Have your say