居中的2x2网格

时间:2013-02-19 21:31:46

标签: html css position

我正在尝试整理一个页面,其中间有一个四个方格的网格。这就是我所拥有的,我想你将能够看到我打算发生的事情。我在这里错过了什么来使定位工作应该如此?

http://jsfiddle.net/LKfd4/

HTML

<div id='main-container'>
 <div class='box' id='topleft'></div>
 <div class='box' id='topright'></div>
 <div class='box' id='bottomleft'></div>
 <div class='box' id='bottomright'></div>

</div>

CSS

#main-container{
    border:1px solid black;
    width:980px;
    height:700px;
    margin:0 auto;
    position:relative;
    top:20px;
}

.box {
    width:100px;
    height:100px;
    background:gray;
    border:2px solid #696969;
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;  
}

#topleft{
    position:relative;
    margin:0 auto;
    top:50%;
    left:50%;
    margin-top:-110px;
    margin-left:-110px;
}
#topright{
    position:relative;
    margin:0 auto;
    top:50%;
    left:50%;
    margin-top:-110px;
    margin-left:10px;
}
#bottomleft{
    position:relative;
    margin:0 auto;
    top:50%;
    left:50%;
    margin-top:10px;
    margin-left:10px;
}
#bottomright{
    position:relative;
    margin:0 auto;
    top:50%;
    left:50%;
    margin-top:10px;
    margin-left:-110px;
}

1 个答案:

答案 0 :(得分:5)

position: relative;#topleft#topright#bottomleft移除#bottomright。并将position: absolute;添加到.box

jsfiddle:http://jsfiddle.net/G85fM/

udpated jsfiddle(关于@Neils评论):http://jsfiddle.net/G85fM/1/