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 top of each other).
<div class="wrap">
<div class="thing"> thing1 </div>
<div class="thing"> thing2 </div>
...
</div>
The columns need to be evenly distributed so that no column is empty. This would be very easy using:
.wrap {
column-count: 4;
column-fill: balance;
}
However, column-fill
only works in Firefox, I believe.
Is there another CSS method to achieve this layout in all recent versions of browsers? Specifically, would flexbox be able to help here?
Please note that I cannot add extra divs to act as columns, and do not want a JS solution.
Here is a fiddle which has the desired layout except for the even distribution → http://jsfiddle.net/bpdtkmmt/
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 eitherflex-direction: column
andflex-wrap: wrap
or the shorthandflex-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 haveflex-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 thenth-child
ornth-of-type
selector to establish a new flex-basis of50%
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 theHowever, the centering the text in a flexbox remains a problem and you will have to establish the things as flex containers by setting
display
toflex
orinline-flex
with aflex-direction
ofcolumn
, along withtext-align
andjustify-content
properties set tocenter
.http://jsfiddle.net/hxcnoxx9/10/
This CSS should solve your problems.