2017-06-26 146 views
3

我正試圖實現下圖所示的列布局。我需要使用flexbox將子div分隔爲列

  • 最大。 3列
  • 最大。 11個孩子中的一列,然後爲12日的孩子,開始新的一列
  • 在每個奇數行的背景光,並且在每個偶數行

enter image description here

一個黑暗的背景如果沒有足夠的孩子組成一個新列,其他列應該填補了水平空間,就像這樣:

enter image description here

https://jsfiddle.net/qLx7sun1/

.parent { 
    display: flex; 
    flex-wrap: wrap; 
    justify-content: space-between; 
    /*flex-direction: column; 
    height: calc(20px * 11);*/ 
} 
.parent div { 
    flex: 1 0 31%; 
    max-width: 31%; 
    background: grey; 
    height: 20px; 
    margin-bottom: 1rem; 
} 

這是我到目前爲止;然而,孩子們將父母填充爲行而不是列。如果我取消對flex-direction: column;的評論,那看起來很奇怪。我也沒有設法得到交替的行背景。

我可以通過CSS/flexbox實現嗎?還是必須使用Javascript?

+2

這樣的事情? https://jsfiddle.net/qLx7sun1/1/ –

+1

你也可以使用css列https://jsfiddle.net/qLx7sun1/2/不知道如果這就是你要去的。如果是這樣,我知道,我會提交作爲答案 –

+0

@MichaelCoker謝謝,這更接近我想要實現的,但是我需要在開始新列之前填充11個項目的列。我已經用12個項目的圖像示例編輯了我的問題。 :)另外flexbox是可取的,但不是必須的 – Zephyr

回答

3

首先,您要使用flex-direction: column來獲得一列中的孩子,然後將height定義爲11個孩子的身高,這是他們的身高* 11 +他們的底部邊距。並添加align-content: flex-start以保持列向左對齊,而不是在列之間創建額外的空間。

然後設置兒童,而不是使用flex-basis因爲它是一個列的width,定義margin-right在列之間創造空間,並使用:nth-child(even)(odd)做條帶化。

.parent { 
 
\t display: flex; 
 
\t flex-wrap: wrap; 
 
    flex-direction: column; 
 
    height: calc(20px * 11 + 11rem); 
 
    align-content: flex-start; 
 
} 
 
.parent div { 
 
    width: 31%; 
 
    background: grey; 
 
    height: 20px; 
 
    margin-bottom: 1rem; 
 
    margin-right: 1em; 
 
} 
 

 
.parent div:nth-child(even) { 
 
    background: black; 
 
    color: white; 
 
}
<div class="parent"> 
 
    <div>1</div> 
 
    <div>2</div> 
 
    <div>3</div> 
 
    <div>4</div> 
 
    <div>5</div> 
 
    <div>6</div> 
 
    <div>7</div> 
 
    <div>8</div> 
 
    <div>9</div> 
 
    <div>10</div> 
 
    <div>11</div> 
 
    <div>12</div> 
 
    <div>13</div> 
 
    <div>14</div> 
 
    <div>15</div> 
 
    <div>16</div> 
 
</div>

+0

這太棒了,非常感謝! :D – Zephyr

+0

@Zephyr不客氣:) –