I have an unknown number of child items in a container:
<div class="container">
<div class="child">Item 1</div>
<div class="child">Item 2</div>
<div class="child">Item 3</div>
<div class="child">Item 4</div>
<div class="child">Item 5…</div>
</div>
I would like to stack these items into 2 columns such that they appear:
Item 1 Item 4
Item 2 Item 5
Item 3
I can’t figure out how to do this using CSS grid without knowing the number of grid rows, or with flexbox without setting an explicit height on the container.
Could anyone please suggest a way to do this?
2
Answers
If there is an obligation of using flexbox and grid, then as far as I know, you would require the container’s height (dynamically calculating it using JavaScript or a CSS custom property which you talked about).
I can think of one way to achieve this purely in CSS without any dynamic calculation or knowing the height in advance and that is by using the
column-count
property. With this you don’t need to worry about the number of items that come in. Sharing my solution here for reference in case you’re looking for a solution other than flexbox or grid:try this :
but i’ll use the Javascript as well