user319940
user319940

Reputation: 3317

Repeating CSS grid without defining more grid areas

I'm trying to use CSS grid to layout some content in the following constraints.

I have three divs - all should be 50% wide but div two and three should stack on top of each other next to div 1.

I've managed to achieve this using grid-template-areas, but I'm using PHP to dynamically populate this, so there's no guarantee that there will always be three divs, so if it goes over this amount, I simply want the grid to repeat.

I'm using the following code right now:

.container {
  display: grid;
  grid-template-columns: 50% 50% 50%;
  gap: 0px 0px;
  grid-auto-flow: row;
  grid-template-areas:
    "Grid-1 Grid-2 ."
    "Grid-1 Grid-3 ."
    ". . .";
}

.Grid-2 { grid-area: Grid-2; }

.Grid-3 { grid-area: Grid-3; }

.Grid-1 { grid-area: Grid-1; }


html, body , .container {
  height: 100%;
  margin: 0;
}

.container * {
  border: 1px solid red;
  position: relative;
}

.container *:after {
  content:attr(class);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: grid;
  align-items: center;
  justify-content: center;
}

<div class="container">
  <div class="Grid-1"></div>
  <div class="Grid-2"></div>
  <div class="Grid-3"></div>
</div>

It would also ne nice to not have to give each div that I'm generating a PHP the specific area class. Is this achievable using grid?

Upvotes: 0

Views: 527

Answers (1)

Temani Afif
Temani Afif

Reputation: 272842

Simply like below:

.container {
  display: grid;
  grid-template-columns: 50% 50%; /* 2 columns */
  grid-auto-rows:50vh; /* size of one row*/
}
/* for each 3 divs make the first one span 2 rows */
.container > :nth-child(3n + 1) { grid-row:span 2 }

.container * {
  border: 1px solid red;
  display: grid;
  place-items: center;
}

.container *:after {
  content:"some content";
}

body {
  margin: 0;
}
<div class="container">
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

Upvotes: 1

Related Questions