rooofl rooofl - 1 month ago 5
CSS Question

CSS Grid Template: Fill columns depending on cell’s class

I have a simple grid layout where cells can be 100% or 50% wide. Some cells have a

.left
or
.right
class. Whatever the order of those cells in my HTML tree, is it possible to append it either to the right or left side, depending on their class, until a new full width cell is set?


The code I used so far:

main{
display:grid;
grid-template:"top top" "left right";
}
section{
grid-area:top;
}
section.left{
grid-area:left;
}
section.right{
grid-area:right;
}


Edit: @wuppie367’s answer solves perfectly my problem, here is how this can be done: https://jsfiddle.net/r2myL1bt/

Answer Source

You can achieve it like this. The elements on the right will fill the gaps between the wide elements, so only the order of the wide and left elements matter. The elements on the right will fill the gaps from top to bottom.

.main {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: column;
  width: 240px;
}

.main div {
  margin: 10px;
  width: auto;
  height: 100px;
}

.main .wide {
  grid-column: 1 / span 2;
  background-color: green;
}

.main .left {
  grid-column: 1 / 2;
  grid-row: auto;
  background-color: red;
}

.main .right {
  grid-column: 2 / 3;
  grid-row: auto;
  background-color: blue;
}
<div class="main">
  <div class="wide"></div>
  <div class="left"></div>
  <div class="left"></div>
  <div class="right"></div>

  <div class="wide"></div>
  <div class="right"></div>
  <div class="right"></div>
  <div class="left"></div>
  <div class="left"></div>
</div>