Tompina
Tompina

Reputation: 787

CSS Flexbox 2 columns with different heights

I have the following code:

.wrapper {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

.a {
  background-color: red;
  width: 65%;
}

.b {
  background-color: green;
  width: 35%;
}

.c {
  background-color: blue;
  width: 65%;
  height: 100px;
}

.d {
  background-color: orange;
  width: 35%;
}

.e {
  background-color: teal;
  width: 65%;
}

.f {
  background-color: purple;
  width: 35%;
}
<div class="wrapper container">
  <div class="a">A</div>
  <div class="b">B</div>
  <div class="c">C</div>
  <div class="d">D</div>
  <div class="e">E</div>
  <div class="f">F</div>
</div>

enter image description here

I am trying to make the F be right under D, like this:

enter image description here

The main reason I am doing this instead of 2 separate columns is because I want to be able to arrange the columns in mobile later by using order. Is this possible in Flexbox, or is there another way?

Upvotes: 8

Views: 15360

Answers (2)

Tabraiz Malik
Tabraiz Malik

Reputation: 126

Inspired from Easy-Masonry-Layout-With-Flexbox

Seems to do the job for me

<div id="masonry">
    <img src="irina.jpg" alt>
    <img src="daniella.jpg" alt>
    <img src="karina.jpg" alt>
    …
</div>

div#masonry {
  display: -ms-flexbox;
  -ms-flex-direction: column;
  -ms-flex-wrap: wrap;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 100vw;
  font-size: 0; 
}

div#masonry img { 
    width: 33.3%;
    transition: .8s opacity;
}

Upvotes: 0

Michael Benjamin
Michael Benjamin

Reputation: 371231

In order for a flex column to wrap, you need to define a fixed height on the container. Otherwise, without a breakpoint, the column has no reason to wrap. It will simply expand the container as a single column.

This problem is explained in more detail here:

You're probably better off with a grid solution.

.wrapper {
  display: grid;
  grid-template-columns: 65% 35%;
  grid-template-areas: " a b "
                       " c d "
                       " c f "
                       " c . "
                       " c . "                       
                       " e . " ;}

.a { grid-area: a; background-color: red;    }
.b { grid-area: b; background-color: green;  }
.c { grid-area: c; background-color: blue; height: 100px; }
.d { grid-area: d; background-color: orange; }
.e { grid-area: e; background-color: teal;   }
.f { grid-area: f; background-color: purple; }
<div class="wrapper">
  <div class="a">A</div>
  <div class="b">B</div>
  <div class="c">C</div>
  <div class="d">D</div>
  <div class="e">E</div>
  <div class="f">F</div>
</div>

Browser support is now pretty strong for CSS Grid.

Also, the order property works in both Grid and Flex layouts. But you may not need order in Grid to re-arrange your layout for mobile screens. You can simply use grid properties.

Upvotes: 6

Related Questions