CSS – margin collapsing

In CSS adjoining vertical margins of two or more boxes (these may or may not be siblings), can combine to form a single margin. These boxes must be in-flow block level boxes.

CSS margin collapsing example between siblings

Bottom margin 50px (box1) + top margin 25px (box2) => collapsed margin 50px (higher)

<style type="text/css" media="screen">
body {margin:0;}
.box1 {
  background:lightgreen;
  width:50px; height: 50px;
  margin-bottom: 50px;
}
.box2 {
  background:lightgray;
  width:50px; height:50px;
  margin-top: 25px;
}
</style>
<div class="box1">
</div>
<div class="box2">
</div>
refresh

CSS margin collapsing example between parent and child

This is somewhat counter intuitive can surprise people initially.
Top margin 0 (parent) + top margin 25px (child) => collapsed margin 25px applied to both parent and child.

<style type="text/css" media="screen">
body {margin:0;}
.parent {
  background:lightgreen;
  width:100px; height: 100px;
}
.child {
  background:lightgray;
  width:50px; height:50px;
  margin-top: 20px;
}
</style>
<div class="parent">
<div class="child">
</div>
</div>
refresh

How to avoid CSS margin collapsing example between parent and child

We can add a padding-top of 1px to parent. This way margins will no longer be adjoining and won’t collapse.

<style type="text/css" media="screen">
body {margin:0;}
.parent {
  background:lightgreen;
  width:100px; height: 100px;
  padding-top:1px;
}
.child {
  background:lightgray;
  width:50px; height:50px;
  margin-top: 20px;
}
</style>
<div class="parent">
<div class="child">
</div>
</div>
refresh

Related links

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments