Reputation: 483
Let's say I have 8 divs. I want them to be split into two columns like this if there's enough space (via min-width
):
1 5
2 6
3 7
4 8
However, if I simply set display: inline-block
, they instead get split like this, which is not what I want:
1 2
3 4
5 6
7 8
Ideally, I'm looking for a solution that allows for unequal sizes, so if there's only 6, but #1 and #2 are of double height, the result will look like this:
1 3
1 4
2 5
2 6
Is this possible in pure CSS? Or, if not, how can this be done in JS?
Upvotes: 1
Views: 633
Reputation: 962
You can use CSS Columns to achieve this behavior:
html {
font-size: 62.5%;
}
.columnWrapper div {
display: inline-block;
width: 100%;
height: 10rem;
color: #fff;
text-align: center;
font-size: 5rem;
line-height: 10rem;
background-color: #4caf50;
margin-bottom: 0.5rem;
}
.columnWrapper {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
-webkit-column-gap: 0.5rem;
-moz-column-gap: 0.5rem;
column-gap: 0.5rem;
width: 20%;
margin: 0 auto;
}
@media screen and (max-width: 500px) {
.columnWrapper {
-webkit-column-count: 1;
-moz-column-count: 1;
column-count: 1;
}
}
<div class="columnWrapper">
<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>
Or see this fiddle.
For the case that there are only six elements, see this fiddle (same code).
Upvotes: 2