2012-11-09 155 views
-3

可能重複:
How to center a div in a div?圍繞一個div內

我有了的寬度和100%的高度,它佔據了整個瀏覽器的一大DIV。我還有一個寬度爲1024px,高度爲400px的另一個DIV。我想知道什麼是最好的方法居中水平和垂直的div將是?當瀏覽器調整大小時,我也希望它保持在中心位置。有沒有一個jQuery插件,一些方便的JavaScript或我可以簡單地使用CSS來做到這一點。

標記

.bigdiv{ 
height:100%; 
width:100%; 
background-color:#eee; 
} 
.smalldiv{ 
height:400px; 
width:1024px; 
background-color:#ccc; 
} 

<div class="bigdiv"> 
<div class="smalldiv"></div> 
</div> 

感謝任何幫助和建議!

+7

此問題已回答很多次。嘗試搜索堆棧溢出。關鍵是'position:absolute','margin-left:-width/2','margin-top:-height/2',以及'position:relative'的容器。 – elclanrs

+1

@elclanrs並添加'top:50%; left:50%;'到小格 –

+0

@ gion_13:對!忘了那個。 – elclanrs

回答

0

好了,這是怎麼得到它的中心。

.bigdiv{ 
height:100%; 
width:100%; 
background-color:#eee; 
position:relative; 
} 
.smalldiv{ 
height:400px; 
width:1024px; 
background-color:#ccc; 
position:absolute; 
left:50%; 
top:50%; 
margin-left:512px; 
margin-top:200px; 
} 

<div class="bigdiv"> 
<div class="smalldiv"></div> 
</div> 
-1

使用text-align:center在更大的div 和margin:0 auto 在你內心的div

0

嘗試使用,margin:0 auto;

.smalldiv{ 
height:400px; 
width:1024px; 
background-color:#ccc; 
margin:0 auto; 
} 
0

您可以輕鬆地給margin:auto;給你的孩子DIV您想要的結果

HTML

<div class="bigdiv"> 
<div class="smalldiv"></div> 
</div> 

CSS

.bigdiv{ 
    height:100%; 
    width:100%; 
    background-color:#eee; 
    } 
    .smalldiv{ 
    height:400px; 
    width:1024px; 
    background-color:#ccc; 
    margin:auto; 
    } 

DEMO

+0

你也必須添加html {height:100%;} body {height:100%;}到CSS。但它不起作用,因爲邊距自動在垂直方向上不起作用。使用我在下面發佈的。 –