2013-12-22 64 views
4

我想要實現的定位是這樣的(這些按鈕,但它並不重要):CSS:Flex的兒童寬度和浮動

|-------|-------|-------|-------| 
|  |  | small |  | 
|  |  |-------|  | 
| big | big | small | big | 
|-------|-------|-------|-------| 

所以,我把它叫做定位從上到下,從左到右 - 如果有足夠的地方,瀏覽器應該把元素放在前一個元素之下,否則 - 放在它旁邊。我不知道會有多少元素,也不知道它們的寬度等等 - 它必須非常靈活。

經過簡短的研究,我發現display: flex。它看起來非常有前途(我不需要與不同瀏覽器兼容 - 我的計劃是使用html來完成本地應用程序),但有一個問題。

注意:我不希望它佔用100%的寬度 - 它只應佔用足夠的空間。父母上的float: left似乎是完美的。

在簡單情況下:大按鈕,大按鈕,小按鈕,大按鈕 - 它的工作原理非常完美。當我再添加一個小按鈕時會出現問題 - 顯示正確 - 在前一個但是父母更大!

這裏是代碼我(和小提琴這裏,這說明這兩種情況:http://jsfiddle.net/h7SK7/):

<div class="container"> 
    <button>Lorem</button> 
    <button class="small">Dolor</button> 
    <button class="small">Sit</button> 
    </div> 

div.container { 
    height:50px; 
    display: flex; 
    flex-direction: column; 
    flex-wrap: wrap; 
    float:left; 
} 

button { 
    height:50px; 
} 

button.small { 
    height:20px; 
} 

誰能幫助我?

回答

0

嘗試把小按鈕放在div中。像這樣JSFiddle

<div class="container"> 
     <button>Lorem</button> 
     <div class="box"> 
      <button class="small">Dolor</button> 
      <button class="small">Sit</button> 
     </div> 
</div> 

.box{ 
    width:70px; 
} 
+0

這顯然解決辦法工作,但我希望我能使用JS切換'small'階級和一切都被動態地重新定位:( – Andy

0

Flexbox不是爲了儘可能地包裝兒童。它僅用於水平或垂直堆疊兒童(彈性物品)。要獲得所需的佈局,您必須使用多個嵌套柔性盒。從CSS Flexible Box Layout Module

摘要
...
孩子的水平和垂直對齊可以很容易被操縱。可以使用這些框的嵌套(水平內部垂直,或水平內部垂直)來構建二維佈局。

因此,要獲得你想要的佈局,必須換兩個小按鈕進入Flexbox的,改變containerflex-direction: row

<div class="container"> 
    <button>Lorem</button> 
    <div class="small"> 
     <button>Dolor</button> 
     <button>Sit</button> 
    </div> 
</div> 
div.container { 
    display: flex; 
    flex-direction: row; 
} 
div.small { 
    display: flex; 
    flex-direction: column; 
} 
div.small button { 
    height:20px; 
} 

瞭解改JSFiddle

更新:

也許,CSS multi-column layouts可以實現所需的佈局。至少在你的按鈕,它似乎工作

<div class="container"> 
    <button>Lorem</button> 
    <button class="small">Dolor</button> 
    <button class="small">Sit</button> 
    <button>Amet</button> 
</div> 
.container { 
    -moz-column-width: 50px; 
    -webkit-column-width: 50px; 
    column-width: 50px; 
} 
button { 
    width: 60px; 
    height: 50px; 
} 
button.small { 
    height: 20px; 
} 

JSFiddle

+0

它不能滿足我,因爲它確實使切換按鈕從小到大變得非常困難:(我不需要flexbox,但可能沒有其他選擇了嗎? – Andy

+0

也許多列布局適合您,請參閱更新的答案。 –