使用flexbox将子div拆分为列

Zep*_*hyr 4 html javascript css flexbox

我正在尝试实现下图所示的列布局。我需要

  • 最高 3列
  • 最高 一列中有11个孩子,然后第12个孩子开始新的一列
  • 每个奇数行上的背景为浅色,每个偶数行上的背景为暗色

在此处输入图片说明

如果没有足够的孩子组成一个新列,其他列应填满水平空间,就像这样:

在此处输入图片说明

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;
}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所拥有的;但是,子级将父级填充为行而不是列。如果我取消注释,flex-direction: column;那看起来真的很奇怪。我也没有设法获得交替行的背景。

我可以通过CSS / flexbox实现此功能还是必须使用Javascript?

Mic*_*ker 6

首先,您要使用flex-direction: column将子项放在一列中,然后将其定义height为11个子项的高度,即它们的高度* 11 +其底边距。并添加align-content: flex-start以使列与左侧对齐,而不是在列之间创建额外的空间。

然后设置width子项的,而不是使用flex-basis它,因为它是一列,定义一个margin-right在列之间创建空间,然后使用:nth-child(even)(odd)进行分割。

.parent {
	display: flex;
	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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)