Collapsing Margins

Very often when a webpage is built, CSS is not given the attention it deserves. Having your CSS well structured, maybe with the help of sass, will definitely boost development and improve maintainability. But thats not all, to develop faster, good knowledge of CSS is essential. Simple problems can give headaches to developers unaware of the CSS ins-and-outs.

Collapsing Margins is definitely one of CSS’s strangest behaviors, and very likely to happen. Checkout this example:

No vertical margins, except the outer element has a 10px margin. What happens is that when two vertical margins (top or bottom) touches, only the biggest margin is used and given to the first/outer element. The margins are only summed when one has a negative value.

If this behavior is not desirable, you have to make sure the vertical margins are not adjoining. You can achieve this by doing:

  • floated elements
  • absolutely positioned elements
  • inline-block elements
  • elements with overflow set to anything other than visible (They do not collapse margins with their children.)
  • cleared elements (They do not collapse their top margins with their parent block’s bottom margin.)
  • the root element
  • adding a border or padding

The only thing changed with the previous example is a padding; no touching margins anymore!!

Finally, Internet Explorer ( version 7 and below ) will not collapse margins when the elements have a layout (for example if the elements have a width or height)

Please checkout the Box Model documentation!


One Response to Collapsing Margins

  1. Pingback: jesse