Search code examples
cssflexboxcss-gridmasonry

How to align items vertically by columns, BUT not align them horizontally inside columns


I made a sketch of the layout that I need to make: drawing of the desired layout

My problem is: how to make articles "4" and "5" position themselves according to the height of the article which is positioned above them, and are not aligned

I tried with these 3 solutions without success:

  1. With CSS Grid: CSS grid allows me to position the 5 elements as desired EXCEPT this height alignment problem! With CSS grid, elements "4" and "5" are aligned regardless of the height of element "2" and "3"

  2. With CSS Flex: CSS flex allows me to position the 5 elements as desired EXCEPT this height alignment problem!

I got help from this page but even using "align-items" and "align-self" I can't get items "4" and "5" to rise proportionally to the height of items "2" and "3"

  1. MASONRY: I also tried with this method:

    Masonry method URL
    DEMO url

    This method uses columns in CSS:

    .masonry { /\* Masonry container \*/
    column-count: 4;
    column-gap: 1em;
    }
    
    .item { /\* Masonry bricks or child elements \*/
    background-color: #eee;
     display: inline-block;
    margin: 0 0 1em;
    width: 100%;
    }
    

My problem with this method is that the items display in order vertically inside the columns

This is a news site and the order in which the elements are displayed is very important: the elements must be displayed in order horizontally


Solution

  • Try this:

    .container {
      display: flex;
      justify-content: center;
      width: 100%;  
    }    
    .item {
      background-color: green;
      margin: 10px;
    }
    .col {
      display: flex;
      flex-direction: column;
    }
      <div class="container">
        <div class="col col1">
          <div class="item">Item 1</div>
        </div>
        <div class="col col2">
          <div class="item">Item 2</div>
          <div class="item">Item 4</div>
        </div>
        <div class="col col3">
          <div class="item">Item 3</div>
          <div class="item">Item 5</div>
        </div>
      </div>