2013-10-15 47 views
0

這裏的全屏結果:http://jsfiddle.net/anik786/UYkSf/4/embedded/result/如何在不知道寬度的情況下水平居中div?

這裏的HTML/CSS:http://jsfiddle.net/anik786/UYkSf/4/

這裏的HTML:

<div class="gallery_container"> 
<div class="pic"> 
    <img src="http://petapixel.com/assets/uploads/2012/02/sample1_mini.jpg" /> 
</div> 
<div class="pic"> 
    <img src="http://www.ndaccess.com/Sample/Images/Image1.jpg" /> 
</div> 
<div class="pic"> 
    <img src="http://petapixel.com/assets/uploads/2012/02/sample1_mini.jpg" /> 
</div> 
<div class="pic"> 
    <img src="http://www.ndaccess.com/Sample/Images/Image1.jpg" /> 
</div> 
<div class="pic"> 
    <img src="http://petapixel.com/assets/uploads/2012/02/sample1_mini.jpg" /> 
</div> 
<div class="pic"> 
    <img src="http://www.ndaccess.com/Sample/Images/Image1.jpg" /> 
</div> 

而CSS:

* {margin: 0; padding: 0;} 

body {background: black;font-family: arial;} 
.gallery_container{ 
/* Insert styles here to make container center on page */ 
} 
.pic { 
height: 300px; 
width: 300px; 
overflow: hidden; 
margin: 20px; 
border: 10px solid white; 
float: left; 
} 

.pic img{ 
height: 300px; 
width: 300px; 
} 

問題是 當窗口大小在一定的寬度時,右側的空間太多(通過調整瀏覽器大小來調整全屏效果)。

所以我試圖中心集裝箱,這樣的畫廊總是在屏幕的中間。我通常使用:

保證金:0汽車;

但是我不能用這個,因爲我不知道該容器的寬度將是什麼(因爲它依賴於窗口大小)。

請幫忙!提前致謝!

回答

0

有許多方法,以中心元件:

保證金方式:

隨着一組寬度或顯示:內聯塊;你可以使用:

margin-left: auto; 
margin-right: auto; 

文本對齊方式:

您可以添加此父:

text-align: center; 

絕對方式:

position: absolute; 
left: 50%; 
margin-left: width/2; 

position: absolute; 
left: 50%; 
transform: translate(0, -50%); 

你將取消對.pic浮動,而是添加display: inline-block的最好方法。然後在父級上添加text-align: center;

+0

感謝這樣一個偉大的答案 –

0

您可以使用display: table將尚未定義給定寬度的項目居中。然後使用margin: 0 auto;

http://jsfiddle.net/LstNS/11/

div { 
    margin: 0 auto; 
    display: table; 
} 
0

也可以使用中心最大寬度

max-width: 80%; 
margin: 0 auto; 

我認爲畫廊會以快速響應的現場反正有%的寬度。

相關問題