Split child divs into columns using flexbox

I am trying to find the column layout shown in the image below. I need

  • Max. 3 columns
  • Max. 11 children in a column, then for the 12th child to start a new column
  • A light background for each odd number line and a dark background for each even number line.

enter image description here

If there are not enough children to create a new column, other columns should not fill the horizontal space, for example:

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;
}

      

This is what I have so far; however, children fill the parent as rows instead of columns. If I uncomment the lines flex-direction: column;

it looks weird. I was also unable to get interleaved line frames.

Can I achieve this with CSS / flexbox or do I need to use Javascript?

+3


source to share


1 answer


First you want to use flex-direction: column

to get the children in the column, then define height

as the height of the 11 children, namely their height * 11 + their bottom margin. And add align-content: flex-start

to align the columns to the left and not create extra space between the columns.

Then set width

for children instead of using flex-basis

as it is a column, define margin-right

to create space between the columns and use :nth-child(even)

or (odd)

to do alternation.



.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;
}
      

<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 codeHide result


+3


source







All Articles