CSS – Preventing Margin Collapse

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

Leave a Reply