0

I'm trying to play with positioning in css and I noticed something that confused me. It's probably a dumb question...but I'm having trouble understanding it.

I created three divs with the width and height of 50px with different background colors. When I position the third div up -60px using margin-top, the third div is on top of the second div. However, when I make the first and second divs inline elements, then both the first two divs are now on top of the third one.

Can someone please explain this concept to me?

<head>
 <style>
    <!-- Divs with the same width and height. Second one where both the first two divs are inline below this one. -->
    #one{
    background-color:red;
    width:50px;
    height:50px;  

     }

    #two{background-color:blue;
    width:50px;
    height:50px; 
     }

    #three{background-color:green;
    width:50px;
    height:50px;
    margin-top:-60px; 
     }
 </style>
</head>
<body>
  <div id="one">
  </div>
  <div id="two">
  </div>
  <div id="three">
  </div>
</body>

<head>
 <style>
    <!-- First two divs are inline  -->
    #one{
    background-color:red;
    width:50px;
    height:50px;  

     }

    #two{background-color:blue;
    width:50px;
    height:50px; 
     }

    #one, #two{display:inline-block;}

    #three{background-color:green;
    width:50px;
    height:50px;
    margin-top:-60px; 
     }
 </style>
</head>
<body>
  <div id="one">
  </div>
  <div id="two">
  </div>
  <div id="three">
  </div>
</body>
user3029001
  • 389
  • 3
  • 6
  • 15

1 Answers1

1

I think there are two issues going on here. One is that by leaving the third div display:block it will naturally wrap the first two divs. For a quick primer on blockvs inline-block see here.

The second part of this is that you have margin-top: -60px while having height: 50px. The negative margin is basically moving it higher up the page. This means the green box will apear 10px higher than the red one (-60 + 50 = -10).

Example Fiddle - I've added margin-left: -5px; and you can see the third div peeking out from under the first.

Community
  • 1
  • 1
badAdviceGuy
  • 2,060
  • 1
  • 16
  • 12