2014-09-26 37 views
1

我目前正在製作一個網站而不使用框架,但是我遇到了問題。即使容器本身位於容器的中心,我的容器也不會在容器中居中。集裝箱中的浮動div

的Html

<body> 
<div id="content"> 
<div class="box"> 

</div> 
<div class="box"> 

</div> 
<div class="box"> 

</div> 
<div class="box"> 

</div> 
</div> 

的CSS

#content{ 
    width: 90%; 
    height: 100%; 
    margin: 0 auto; 
} 

.box{ 
    width: 400px; 
    height: 150px; 
    float: left; 
    border: 1px solid #c8c8c8; 
    border-radius: 3px; 
    margin: 13px; 
} 

的div被完全集中時,我有我的窗口,全寬,但一旦我調整它的大小,他們只是重組無定心。

調整前:http://cl.ly/image/2y2g2W0n230g/Screen%20Shot%202014-09-26%20at%2021.50.21.png

我曾嘗試不同的方法當談到定位我感到困惑,解決它,比如做margin: 0 -10%;margin: 0 25%;http://cl.ly/image/241R2I24280w/Screen%20Shot%202014-09-26%20at%2021.49.23.png 調整窗口後。 謝謝。

回答

2

只要改變你的CSS這樣的,這樣你可以在很多方面適應你的盒子和預期他們會以響應佈局作出反應:

#content { 
    width: 90%; 
    height: 100%; 
    margin: 0 auto; 
    text-align:center; 
    display:block; 
} 
.box { 
    width: 45%; 
    height: 150px; 
    display:inline-block; 
    border: 1px solid #c8c8c8; 
    border-radius: 3px; 
    margin: 13px 2%; 
} 

See fiddle here

說明:

我已經刪除了您的浮動塊,使用了塊元素並按百分比替換了固定大小。然後,我在容器箱#content中使用了一個text-align:center屬性,所以一切都很好地在該容器的中心對齊。現在,如果你調整,列將屏幕寬度的45%,但你可以通過媒體查詢明顯改變的行爲,並使用類似.box{display:box}爲小屏幕

+0

Hello ,它幾乎是完美:)我編輯了一下,以保持原來的寬度(我不希望箱子變小)。我也很欣賞這個小提琴的例子! '.box {width:400px; height:150px; display:inline-block; border:1px solid#c8c8c8; border-radius:3px; margin:12px 1%; }' – CodexVideos 2014-09-26 20:06:25

+0

等待,在這種情況下,保持寬度爲45%,只需添加'最小寬度:400px' – Devin 2014-09-26 20:07:50

+0

哦好吧謝謝!另外請注意,我也非常欣賞這個解釋,幫助我,因爲我不擅長定位。 – CodexVideos 2014-09-26 20:08:46

0

2解決方案: 您可以使用寬度的百分比boxes

#content{ 
    width: 90%; 
    height: 100%; 
    margin: 0 10%; 
} 

.box{ 
    width: 30%; 
    height: 150px; 
    float: left; 
    border: 1px solid #c8c8c8; 
    border-radius: 3px; 
    margin: 13px; 
} 

箱子會調整內容的大小,但箱子裏的東西可能看起來很奇怪的小尺寸。

或 您可以使用像素值爲您的content的寬度。而調整

#content{ 
    width: 1200px; 
    height: 100%; 
    margin: 0 10%; 
} 

.box{ 
    width: 400px; 
    height: 150px; 
    float: left; 
    border: 1px solid #c8c8c8; 
    border-radius: 3px; 
    margin: 13px; 
} 

的寬度框中不會改變,也不在它的東西,但可以在小屏幕上是痛苦的。

1

您的問題有多種解決方案。根據你在這些盒子裏面的內容,這可能是最簡單的一個:text-align:centerdisplay:inline-block組合;看這裏。 Fiddle

+0

我正在考慮用圖像填充它們並用標題覆蓋 – CodexVideos 2014-09-26 20:01:32

+0

繼續嘗試。如果它不起作用,請從小提琴中添加註釋的css。如果這樣做不起作用,請參閱其他選項。 – 2014-09-26 20:04:27

+0

謝謝我嘗試過你的小提琴,它的工作完美! – CodexVideos 2014-09-26 20:09:16

0

添加自動利潤率爲你的箱子

.box{ 
    width: 400px; 
    height: 150px; 
    border: 1px solid #c8c8c8; 
    border-radius: 3px; 
    margin-top: 13px; 
    margin-left:auto; 
    margin-right:auto; 
    } 
0

我在我的機器上創建了你的文件,並且div不居中,所以我假設你的屏幕或分辨率設置不同,或者你的內容容器在一個或多個其他div中?

無論如何,嘗試添加'clear:left;'在你的盒子類代碼中,它應該可以解決你的問題(把它放在'float:left'的上面,祝你好運!