0

I gave margin 20px for both the div inside sidebar div. But for some reason the gap between two div's us just 20px, which should be 40px. 20px from box1 and 20px from box2. Am I missing some minor thing. please point it out.

Fiddle:

http://jsfiddle.net/3UJWf/

HTML:

<div class="sidebar">
     <div class="box1 common">
         <p>Text is here</p>
     </div>
     <div class="box2 common">
         <p>Text is here</p>
     </div>
</div>

CSS:

*
{
    padding:0px;
    margin:0px;
}
.box1 {
    background:red;       
    padding: 40px;
    width: 300px;
}
.box2 {
    background: green;       
    padding: 40px;
    width: 300px;
}
.common {
    margin: 20px;
}
Susheel Singh
  • 3,824
  • 5
  • 31
  • 66

3 Answers3

2

This is in the CSS 2.1 specification

"In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin."

Source

The best solution is to stick a clearfix between the two divs.

Community
  • 1
  • 1
Andy
  • 4,538
  • 2
  • 26
  • 34
1

try using .common{ display: inline-block } and give the sidebar a width. solves the problem for me

electrophanteau
  • 1,322
  • 10
  • 12
1

Check Demo

CSS Margin Collapsing

float:left; or display: inline-block solves the above issue

Let’s explore exactly what the consequences of collapsing margins are, and how they will affect elements on the page.

The W3C specification defines collapsing margins as follows:

In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding, or border areas, or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.

In simple terms, this definition indicates that when the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero.1 In the case where one element has a negative margin, the margin values are added together to determine the final value. If both are negative, the greater negative value is used. This definition applies to adjacent elements and nested elements.

There are other situations where elements do not have their margins collapsed:

  1. floated elements
  2. absolutely positioned elements
  3. inline-block elements
  4. elements with overflow set to anything other than visible (They do not collapse margins with their children.)
  5. cleared elements (They do not collapse their top margins with their parent block’s bottom margin.) the root element

This is a difficult concept to grasp, so let’s dive into some examples.

Community
  • 1
  • 1
codefreaK
  • 3,584
  • 5
  • 34
  • 65