How to create UI with different size rows in CSS with grid/flex?

Viewed 101

I need to create a UI as in the diagram, which will change its layout depending on the class passed to its elements (2 views).

  1. the first layout looks like two columns, in the first column 2 divs (a and b) one on top another without a gap and the third div (c) in the second column aligned to the top.

  2. the second layout - all 3 divs are in one column but the div from the second column(c) enters in between them (a and b)

I tried to use grid css and 2 columns for the first layout (grid-template-columns: auto auto) to turn it to one column in the 2nd view (grid-template-columns: auto) but the problem is that C block is longer than A so the grid row lengthens according to the longest div so there is a big gap between A and B. Any ideas preferably using flex or grid?

diagram

.a {
  width: 50px;
  height:30px;
  background: pink;
}

.b {
  width: 50px;
  height:80px;
  background: green;
}

.c {
  width: 50px;
  height:80px;
  background: red;
}

.cont {
  display: grid;
  grid-template-columns: auto auto;
  width: 120px;
}
<div class="cont">

<div class="a">A
</div>

<div class="c">C
</div>

<div class="b">B
</div>

</div>

1 Answers

The problem is that you're dealing with only two rows. An auto-sizing row will take the height of the tallest item. This will create a gap between shorter items and the bottom of the row.

Take a different approach:

  • Break down the rows to a common multiple for each grid item (i.e., 10px).
  • Have each item span across rows to achieve their height.

.cont {
  display: grid;
  grid-template-columns: 50px 50px;
  grid-auto-rows: 10px;
  grid-gap: 10px;
  width: 120px;
}

.a {
  grid-row: 1 / span 3;
  grid-column: 1;
  background: pink;
}

.b {
  grid-row: 4 / span 8;
  grid-column: 1;
  background: green;
}

.c {
  grid-row: 1 / span 8;
  grid-column: 2;
  background: red;
}
<div class="cont">
  <div class="a">A</div>
  <div class="b">B</div>
  <div class="c">C</div>
</div>

Related