Search code examples
csshtmlcenter

why is my center <div> is not aligned with my left <div> and right <div>?


I'm trying to put three div together. One is on the left, one is in the middle, and one is on the right.

However, I'm experiencing a problem that the middle is not aligned properly.

My current HTML code:

 <div class="three_contents">
     <div class="left">Left</div>
     <div class="right">Right</div>
     <div class="center">Center</div>
 </div>

My current CSS code:

.three_contents{
width: 900px;
border: 0px solid #000;
}

.left{float: left;
margin-top: 25px;
width: 290px;
height: 290px;}

.right{float: right;
margin-top: 25px;
width: 290px;
height: 290px;}

.center{display:block;
margin: 25px auto;
width: 290px;
height: 290px;}

However, when I add a 1px border in the the three_contents div, and the middle div is aligned. I have attached two screenshots and hopefully someone can help me to resolve this issue. Thanks a lot.

Problem with the middle div isn't aligned:

http://i41.tinypic.com/250sg3p.png

After I add the 1px border, and the middle div is aligned:

http://i43.tinypic.com/vy9lqq.png


Solution

  • Put the margin only on the center div. Like so:

    .three_contents
    {
        width: 900px;
        border: 0;
    }
    
    .left
    {
        float: left;
        border: solid 1px;
        width: 290px;
        height: 290px;
    }
    
    .right
    {
        float: right;
        border: solid 1px;
        width: 290px;
        height: 290px;}
    
    .center
    {
        margin: 25px auto;
        display:block;
        border: solid 1px;
        width: 290px;
        height: 290px;
    }
    

    I made a fiddle to show you this: http://jsfiddle.net/stakL/1/

    EDIT: To be sincere, I also don't quite understand why it happens. But I can see that the margin-top property set on the left and right div's was taking the middle div's top position as the reference point to apply that margin.

    On other words, the center div was 25px from the top, and the left and right div's were 25px from the middle div's top.