Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css grid - variable span of elements

Tags:

css

css-grid

I'm trying to do the following grid:

1/3 | 1/3 | 1/3   (3 equal elements)
   1/2 | 1/2      (2 equal elements)
   1/2 | 1/2      (2 equal elements)

For that reason I need to split each row into 6 columns to accommodate both 1/2 and 1/3. I seem to be misunderstanding the grid-column command while I want to set how many columns each element takes. The following code does not work properly.

.grid-front {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: 1fr 1fr 1fr;
  grid-gap: 1em;
}

.grid-front > div {
  background-color: red;
}
.top-left {
  grid-column: 1 / 3;
}

.top-centre {
  grid-column: 3 / 5;
}

.top-centre {
  grid-column: 5 / 7;
}
<section class="grid-front">
   <div class="top-left">1</div>
   <div class="top-centre">2</div>
   <div class="top-right">3</div>
   <div class="middle-left">4</div>
   <div class="middle-right">5</div>
   <div class="bottom-ll">6</div>
   <div class="bottom-lr">7</div>
   <div class="bottom-right">8</div>
 </section>

It displays all the grid elements. First element (top-left) takes 2 'spaces', then there's a white gap (spanning 2 spaces) where the second element should be. Then there's a 2nd element (spanning 2 spaces) where the 3rd should have been. Then there are the remaining elements spread evenly in the second row.

What am I misunderstanding about it?

like image 969
Wasteland Avatar asked Apr 27 '26 13:04

Wasteland


1 Answers

You have .top-centre declared 2x. The second version is overriding the first.

.grid-front {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: 1fr 1fr 1fr;
  grid-gap: 1em;
}

.grid-front>div {
  background-color: red;
}

.top-left {
  grid-column: 1 / 3;
}

.top-centre {
  grid-column: 3 / 5;
}

/* ADJUSTMENT */
.top-right {
  grid-column: 5 / 7;
}
<section class="grid-front">
  <div class="top-left">1</div>
  <div class="top-centre">2</div>
  <div class="top-right">3</div>
  <div class="middle-left">4</div>
  <div class="middle-right">5</div>
  <div class="bottom-left">6</div>
  <div class="bottom-right">7</div>
</section>
like image 153
Michael Benjamin Avatar answered Apr 30 '26 10:04

Michael Benjamin