0

div
     {
       margin:10px 0px 20px 0px;
       border:1px solid green;
       height:30px;
     }
<div>1</div>
     <div>2</div>
     <div>3</div>
     <div>4</div>

If you look at my above code, I have applied margin-top 10px and margin-bottom 20px. I am expecting the output like each div should have the margin:30px(20px from prev div + 10px from current div) like how padding is working. But I am getting only 20px gap? Why?

Suresh Ponnukalai
  • 13,820
  • 5
  • 34
  • 54
  • 4
    Margins [collapse](https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing). [This is a good explanation](http://stackoverflow.com/a/3070007/300836) of the reason why they're designed to do that. – Matt Gibson Jul 22 '14 at 12:14

2 Answers2

0

When you have two block elements with bottom and top margin, margin are collapsed.

In real life it means, that only the higher one is used to create a gap between elements. In this case the gap is 20px.

If you want to have there 30px, elements has to have float or display: inline-block, or one of these margins has to be set to 30px.

Here is example with float (for inline-block it will be the same) elements as I wrote above. Margin between them is 30px. Remember, in both cases width has to be set.

<style>
    div {width: 100%; height: 30px; float: left; clear: left; margin: 20px 0 10px; border: 1px solid red}
</style>

<div>1</div>
<div>2</div>

http://jsfiddle.net/6WHVU/1/

pavel
  • 26,538
  • 10
  • 45
  • 61
0

use display:inline-block

div
{
 margin:10px 0px 20px 0px;
 border:1px solid green;
 height:30px;
    display:inline-block;
    width:100%;
}

http://jsfiddle.net/akash4pj/q2BDa/2/