1

html:

    <div class="outside">
         <div class="inside">
         </div>
    </div>

I have two CSS : #1 and #2

 /*CSS#1 does not work*/
.outside{
    background: blue;
    width: 400px;
    height: 400px;
}
.inside{
    background: red;
    width: 200px;
    height: 200px;
    position: relative;
    top: 50%;
    margin: 0 auto;
    margin-top: -100px; /*half height of this div*/
}

/*CSS#2 works well */
.outside{
    border: 1px solid black;
    width: 400px;
    height: 400px;
}
.inside{
    background: red;
    width: 200px;
    height: 200px;
    position: relative;
    top: 50%;
    margin: 0 auto;
    margin-top: -100px; /*half height of this div*/
}

My aim is to place the 'inside' div at the center of the 'outside' div (both vertical and horizontal). I have a lot of ways to achieve this aim, however I found something strange during the process.

I found that CSS#2 works quite well, but CSS#1 does not work: when setting the 'inside' div 'margin-top: -100px', the 'outside' also moves up..

Here is the demo

So I am wondering why 'border' works well here and why 'background' does not work?

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Ding Arne
  • 11
  • 2
  • At end, the problem is solved successfully by Mr.Allen's kind help. And I found a very nice paragraph which is about callapsing margin: http://reference.sitepoint.com/css/collapsingmargins :) – Ding Arne Dec 17 '13 at 06:35

2 Answers2

0

You need to add overflow: auto; to the parent element there, but however your approach is incorrect, you need to position your child element absolute to the parent element and not relative

Demo


Using overflow: auto; or border will fix your issue as it prevents collapsing of the parent margin.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • You are right, thank you very much for your help! I know the 'absolute' way, but do not know why 'overflow: auto' works here.. may you explain it for me ... thank you! I also feel confused why 'border: 1px solid black' works well even without 'overflow: auto'.... – Ding Arne Dec 17 '13 at 05:03
  • @DingArne http://stackoverflow.com/questions/102640/css-margin-collapsing It prevents collapsing margin – Mr. Alien Dec 17 '13 at 05:12
  • Thank you, Mr.Alien. I think I got my answer through your help! I will dig into the resources you provided, thanks! – Ding Arne Dec 17 '13 at 05:16
0

Try this. You need to set top and left as 25 %. I have tested it on ie 11 and crome.It is working fine.

.outside{
    background: blue;
    width: 400px;
    height: 400px;
}
.inside{
    background: red;
    width: 200px;
    height: 200px;
    position: relative;
    top: 25%;
    left:25%;

}
Priyank
  • 1,353
  • 9
  • 13
  • Thank you, Priyank. This only works for my issue when the 'inside' div has half width&height of the 'outside' div... I am really curious about why 'border: 1px solid black' works well here rather than using 'background: blue' directly. – Ding Arne Dec 17 '13 at 05:14