Search code examples
htmlcssalignmentcss-grid

Css Grid: Center align different number of items in 2 rows


I have to place 7 divs (images) in two rows, 3 in 1st row and 4 in 2nd row. Top 3 divs should be centered and bottom 4 can take all space.

enter image description here

Here is what I did:

.content {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 1fr repeat(3, 170px) 1fr;
  grid-template-areas: ". item1 item2 item3 ."
                       "item4 item5 item6 item7";
  grid-template-rows: 1fr 1fr;
}

.content .box {
   width: 170px;
   height: 170px;
   border: solid 1px #000;
}

.content.box:nth-child(1) {
  grid-area: box1;
}

.content.box:nth-child(2) {
  grid-area: box2;
}

.content.box:nth-child(3) {
  grid-area: box3;
}

.content.box:nth-child(4) {
  grid-area: box4;
}

.content.box:nth-child(5) {
  grid-area: box5;
}

.content.box:nth-child(6) {
  grid-area: box6;
}

.content.box:nth-child(7) {
  grid-area: box7;
}
<div class="content">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
  <div class="box">5</div>
  <div class="box">6</div>
  <div class="box">7</div>
</div>


Solution

  • A grid, as its name implies, must be shaped as a grid. That menas that the number of columns must be the space for all the rows.

    So, your style for areas is not being accepted by the browser, because it has 5 columns for the first row and 4 for the second row.

    @kukkuz has already posted an answer correcting this issue. Here you have another possibility, in my vies more adjusted to your request.

    Anyway, probably the best solution for this layout would be using flex (since the layout is not a real grid )

    .content {
      display: grid;
      grid-gap: 10px;
      grid-template-columns: repeat(8, 100px);
      grid-template-areas: "empt box1 box1 box2 box2 box3 box3 emp2"
                           "box4 box4 box5 box5 box6 box6 box7 box7";
      grid-template-rows: 1fr 1fr;
    }
    
    .content .box {
       width: 180px;
       height: 170px;
       border: solid 1px #000;
    }
    
    .content .box:nth-child(1) {
      grid-area: box1;
    }
    
    .content .box:nth-child(2) {
      grid-area: box2;
    }
    
    .content .box:nth-child(3) {
      grid-area: box3;
    }
    
    .content .box:nth-child(4) {
      grid-area: box4;
    }
    
    .content .box:nth-child(5) {
      grid-area: box5;
    }
    
    .content .box:nth-child(6) {
      grid-area: box6;
    }
    
    .content .box:nth-child(7) {
      grid-area: box7;
    }
    <div class="content">
      <div class="box">1</div>
      <div class="box">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
      <div class="box">5</div>
      <div class="box">6</div>
      <div class="box">7</div>
    </div>