css – Arrange divs in blocks on top of each other?

Question:

I would like to arrange my divs in column form, but not side by side, but one on top of the other. Normally when using float: left or display: inline-block the elements are tiled up to the size limit, then a new line is created, eg:

|DIV 1|   |DIV 2|   |DIV 3|

|DIV 4|   |DIV 5|   |DIV 6|

|DIV 6|   |DIV 7|   |DIV 8|

But I would like them to look like this:

|DIV 1|   |DIV 4|   |DIV 7|

|DIV 2|   |DIV 5|   |DIV 8|

|DIV 3|   |DIV 6|   |DIV 9|

I don't want to have to create different columns and put each div there, I want them to self-organize like this, how can I do it?

Answer:

You can use the column-count property and define how many columns you want, in the example I put 3 columns. The property always tries to optimize the distribution automatically among all three columns, regardless of how many divs you have inside.

Here is the Mozilla documentation for this property https://developer.mozilla.org/en-US/docs/Web/CSS/column-count

See the example to better understand:

.colunas {
    -webkit-column-count: 3; /* Chrome, Safari, Opera */
    -moz-column-count: 3; /* Firefox */
    column-count: 3;
}
<div class="colunas">
    <div>DIV 1</div>
    <div>DIV 2</div>
    <div>DIV 3</div>
    <div>DIV 4</div>
    <div>DIV 5</div>
    <div>DIV 6</div>
    <div>DIV 7</div>
    <div>DIV 8</div>
    <div>DIV 9</div>
</div>

TIP:

It's even super easy to make the columns responsive, as you can change this number depending on the screen width. In the model below, when the screen is smaller than 768px, it changes from 3 to 2 columns

.colunas {
    -webkit-column-count: 3; /
    -moz-column-count: 3; 
    column-count: 3;
}

@media screen and (max-width: 768px) {
    .colunas {
        -webkit-column-count: 2; 
        -moz-column-count: 2; 
        column-count: 2;
    }
}

NOTE:

  • With display:flex you need to set a height for the container
  • With column-count you don't need to define the parent element's height or number of rows
  • With display:grid you need to set an automatic number of rows , as well as the width, it can be an option to consider
Scroll to Top