2016-04-26 87 views
7

我經歷了幾個類似的問題,但答案不適合我。即使分發固定大小的div

我有幾個div,它們每個都有210px的固定寬度。

它們所在的容器可以根據用戶的屏幕大小調整大小。 div必須始終保持均勻的水平間距,如果沒有空間,它也應該將div的行分成另一行。

要了解更多信息,請參閱下圖。 enter image description here

這個JS fiddle已經達到了我想要的結果。但是我不明白它對於我必須具有固定寬度的div是如何工作的。

width: calc(100%/6); 

編輯:

與JS小提琴的問題是,當屏幕尺寸是它有空間,但沒有足夠的空間,以適應另一個DIV。在這種情況下,最後一個div應該更接近右側。

enter image description here

+0

Flexbox來拯救。 –

+0

爲什麼選擇Flexbox?內嵌塊,靜態寬度,百分比裝訂線。 –

+0

@MarcoHengstenberg啊..百分比排水溝! –

回答

2

Flexbox可以通過將justify-content設置爲space-around(或space-between,取決於您的表示需要)來執行您想要的操作。這裏有一個簡單的例子:

body{ 
 
    display:flex; 
 
    flex-wrap:wrap; 
 
    justify-content:space-around; 
 
    margin:0; 
 
    padding:5px; 
 
} 
 
div{ 
 
    background:#000; 
 
    flex:0 0 210px; 
 
    height:210px; 
 
    margin:5px; 
 
    width:210px; 
 
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>

檢查caniuse.com對瀏覽器的支持和前綴細節。

+0

一般正確取決於OP想要最後一行上的框出現。 –

+0

該死的,我真的需要花時間舒適地使用彈性盒子。看起來好像會節省爲這種常見設計模式編寫大量額外的代碼。 – Korgrue

+0

這是一個關於flexbox及其屬性的非常好的初學者教程:https://css-tricks.com/snippets/css/a-guide-to-flexbox/ – Shaggy

0

http://kyusuf.com/post/almost-complete-guide-to-flexbox-without-flexbox

因此,這裏是一篇文章,解釋如何實現可視化的佈局,而無需使用Flexbox的(它附帶了很多的bug,你將不得不在深潛水,使其跨瀏覽器工作始終如一 - 瀏覽器支持變得更糟,當你不修補它的語法時,讓我們假設:「沒有Flexbox!」)。

在手,你的問題的解決方案是相當直截了當,而不Flexbox的:

.container { 
    padding: y%; /* by giving the container a percentage based padding, you will create a slowly upscaling container as screen-width increases */ 
} 

.box { 
    width: 210px; /* whyever they need a fixed width but ok, who knows */ 
    margin-right: x%; /* x should be replaced with a value that distributes your containers evenly across the screen and makes them wrap when needed. Fiddle with the value until it makes sense to you. */ 
} 

這是否解決了問題?

0

如果我指的是屏幕截圖,每個人的想法,Flexbox,就在這裏幫助你

#container { 
 
    margin:1em; 
 
    color:turquoise; 
 
    display:flex; 
 
    flex-wrap:wrap; 
 
    border: solid; 
 
    padding:2vh; 
 
    align-items:center; 
 
    justify-content:space-between; 
 
} 
 
#container > div:before { 
 
    content:'boxe '; 
 
    padding-right:0.25em;; 
 
} 
 
#container > div { 
 
    display:flex; 
 
    
 
    align-items:center; 
 
    justify-content:center; 
 
    min-height:25vh; 
 
    border: solid; 
 
    margin:1vh 0; 
 
    width:400px; 
 
    min-width:calc(100vw/4); 
 
    max-width: 45%; 
 
    
 
}
<div id="container"> 
 
    <div>1</div> 
 
    <div>2</div> 
 
    <div>3</div> 
 
    <div>4</div> 
 
    <div>5</div> 
 
    <div>6</div> 
 
</div>

codepen to play with

(我期待從我的意見其實關於 http://jsfiddle.net/bvgn46hu/108/ & http://jsfiddle.net/bvgn46hu/114/反饋)