1

I've written the following markup and styles:

<div id="parent">
    <div id="child">
    </div>
</div>

#parent{
    width:300px;
    height:300px;
    background:aqua;

}
#child{
    margin: 100px;
    width:500px;
    height:500px;
    background:black;

}

So why doesn't the div#parent appear at the left-top corner, but is moved to the bottom? jsFiddle But if we consider the following jsFiddle then it works as I'm expected.

  • Why is the margin on #child? If you remove it, it should sit on in the top left of the parent by default. – jd182 Jan 26 '14 at 08:15
  • Well, it's difficult to answer without research, but I know for sure that it is expected behavior across all browsers defined by the true specifications. – dachi Jan 26 '14 at 08:22
  • You can read enough here, but I don't think it's useful for anything except basic understanding of stylesheets http://www.w3.org/TR/CSS2/box.html#collapsing-margins – dachi Jan 26 '14 at 08:24
  • 2
    That's a [margin](http://reference.sitepoint.com/css/collapsingmargins) [collapsing](https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing) [issue](http://stackoverflow.com/questions/102640/css-margin-collapsing). – Hashem Qolami Jan 26 '14 at 08:27

1 Answers1

0

margin of #child makes #parent to move.

In first jsfiddle margin,height,width are 100px,500px,500px and in second jsfiddle, margin,height,width are 10px,10px,200px respectively.

Changing margin,height and width would obviously give different output but if you OBSERVE carefully, margin still remains and it does not resolve your issue.

#parent is not at the top-left corner in both cases. You can see yellow color in both fiddles.

Write:

#parent{
    position:relative;
}
#child{
    position:absolute;
}

Updated fiddle here.

codingrose
  • 15,563
  • 11
  • 39
  • 58
  • 1
    I'm repeat my question: **Why** div#parent doesn't appear at the top-left corner. But if we consider the following http://jsfiddle.net/nWF8k/3/ then it works as I'm expected. –  Jan 26 '14 at 08:20
  • @Dmitrii I have updated my answer. Hope it is helpful. – codingrose Jan 26 '14 at 08:31
  • `Why div#parent doesn't appear at the top-left corner. But if we consider the following jsfiddle.net/nWF8k/3 then it works as I'm expected.` Your question was answered by @Hashem above. It's a "margin collapse" issue. The second fiddle displays the *same* behavior, but just not as noticably because the child div has a much smaller top margin. – ralph.m Jan 26 '14 at 13:34