I am trying to achieve the column layout shown in the picture below. I need
If there are not enough children to make up a new column, the other columns should not fill up the horizontal space, like this:
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 the children fill up the parent as rows instead of columns. If I uncomment the flex-direction: column;
lines it looks really weird. I also haven't managed to get the alternating row backgrounds.
Can I achieve this through CSS/flexbox or do I have to use Javascript?
Approach: To create a two-column layout, first we create a <div> element with property display: flex, it makes that a div flexbox and then add flex-direction: row, to make the layout column-wise. Then add the required div inside the above div with require width and they all will come as columns.
For 3 items per row, add on the flex items: flex-basis: 33.333333% You can also use the flex 's shorthand like the following: flex: 0 0 33.333333% => which also means flex-basis: 33.333333% .
First you want to use flex-direction: column
to get the children in a column, then define height
to be the height of 11 children, which is their height * 11 + their bottom margin. And add align-content: flex-start
to keep the columns aligned to the left, instead of creating additional space between the columns.
Then set the width
of the children instead of using flex-basis
since it's a column, define a margin-right
to create space between the columns, and use :nth-child(even)
or (odd)
to do the striping.
.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With