0

My markup looks like so:

<div class="row">
  <div class="cell1">Cell 1</div>
  <div class="cell2">Cell 2<br />Context: cell 2</div>
  <div class="cell3">Cell 3<br />Context: cell 3</div>
  <div class="cell4">Cell 4</div>
</div>

I need to achieve a 2 column grid layout where I can put any of the divs in either column and there will be no vertical gaps. I cannot alter the markup. Example scenarios are visualised below.

Grid layout scenarios

I tried using a grid-template and allowing the child divs to use grid-area in any combination to achieve the multiple desired scenarios. For example:

.row {
  display: grid;
  grid-template: "col1 col2" / 1fr 1fr;
}

.cell1,
.cell3 {
  grid-area: col1;
}

.cell2,
.cell4 {
  grid-area: col2;
}

This allocates divs to columns correctly, but they layer on top of each other inside the areas rather than stack vertically:

Outcome grid layout

Is the desired layout possible?

CaribouCode
  • 13,998
  • 28
  • 102
  • 174
  • CSS grid is 3D, so you need to also specify the element's row. This won't necessarily work well, unless your `cell` elements are of a known quantity and potential height. This is essentially a masonry grid. The third scenario you posted is the easiest, since the left column element (`2`)is shorter than the right column's first element (`1`). You can simply add `grid-template-rows: auto` for that one to work. I also wouldn't necessarily use `grid-template-areas`, since `grid-template-columns: repeat(2,1fr)` would do the same thing and you can assign the `cells` using `grid-column: 1` or `2` – disinfor Jul 07 '23 at 17:13

0 Answers0