1213
1213

Reputation: 756

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/

Upvotes: 0

Views: 481

Answers (2)

wuppie367
wuppie367

Reputation: 362

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>

Upvotes: 1

user8478480
user8478480

Reputation: 435

You could add this css to the classes and if they're both 50% width with no margin or padding, or combined with those make 50% they should sit correctly.

.left{
float:left;
}
.right{
float:right;
}

Upvotes: 0

Related Questions