I have a single div named .wrap
within which items are placed. An unknown amount of items (.thing
) should be arranged into four columns (stacking on to
Yes, you can use Flexbox here—and it should get the job done for the most part. It's sort of hacky and you have abandon using CSS column rules. There is somewhat less variability, so if you add any further rows/columns, you will have to change values. In order to preserve the number of columns per row, you will need to set a fixed or percentage height for the wrapper. From there, you establish the wrapper container as a flex container with the display: flex
rule and establish multiple columns using either flex-direction: column
and flex-wrap: wrap
or the shorthand flex-flow: column wrap
.
To make sure each column has x number of items in it, you will need to use the flex-basis
rule and set to the percentage of the column you want to fill up. So a column with 3 items would have flex-basis: 33.33%
. You indicated you want several rows of 3 items then a couple of rows of 2 items, so will need to use the nth-child
or nth-of-type
selector to establish a new flex-basis of 50%
starting at the 10th element. And of course, you will have to establish a percentage for the width you want the thing element to take up on the page (4 rows = 25%). To make sure all elements are equally sized, you need to use the
However, the centering the text in a flexbox remains a problem and you will have to establish the things as flex containers by setting display
to flex
or inline-flex
with a flex-direction
of column
, along with text-align
and justify-content
properties set to center
.
justify-content: center;
flex-direction: column;
text-align: center
http://jsfiddle.net/hxcnoxx9/10/
This CSS should solve your problems.
.wrap {
height: 180px;
background: linear-gradient(to right, tomato 0%, tomato 25%, slategrey 25%, slategrey 50%, tomato 50%, tomato 75%, slategrey 75%);
display: flex;
flex-direction: column;
flex-wrap: wrap;
}
.thing {
background: rgba(255, 255, 255, .2);
color: #fff;
width: 25%;
flex-basis: 33.33%;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
display: inline-flex;
justify-content: center;
flex-direction: column;
text-align: center;
}
.thing:nth-child(1n+10) {
flex-basis: 50%;
}