Search code examples
htmlcsscss-gridcentering

Center grid item on wrap


I am trying to figure out how to center a a 3rd div. So on full width i have 3 boxes in a grid. They are 400px in width. When the width is 1220px that turns into 2 boxes in a row. So my 3rd box is aligned to the left. How do i center it without ruining the width. Because i tried margin: 0 auto and it just made it as wide as the stuff inside it.

here is my code:

.wraper {
  display: grid;
  grid-template-columns: 400px 400px 400px;
  grid-gap: 10px;
  grid-template-columns: repeat(3, 400px);
}

.box {
  background-color: red;
  height: 200px;
}

@media (max-width: 1220px) {
  .wraper {
    grid-template-columns: repeat(2, 400px);
  }
}

@media (max-width: 810px) {
  .wraper {
    grid-template-columns: repeat(1, 400px);
  }
}

@media (max-width: 400px) {
  .wraper {
    grid-template-columns: repeat(1, 300px);
  }
}
<div class="block bg-success">
  <h1>Projects</h1>
  <div class="wraper">
    <div class="box">A</div>
    <div class="box">B</div>
    <div class="box">C</div>
  </div>
</div>


Solution

  • In your 1220px media query, add a rule to center the third div.

    @media (max-width: 1220px) {
      .wrapper {
        grid-template-columns: repeat(2, 400px);
      }
    
       /* NEW */
      .box:last-child {
        grid-column: 1 / 3;
        justify-self: center;
        width: 400px;
      }
    }
    

    jsFiddle demo

    .wrapper {
      display: grid;
      grid-template-columns: 400px 400px 400px;
      grid-auto-rows: 200px;  
      grid-gap: 10px;
      grid-template-columns: repeat(3, 400px);
    }
    
    @media (max-width: 1220px) {
      .wrapper {
        grid-template-columns: repeat(2, 400px);
      }
    
       /* NEW */
      .box:last-child {
        grid-column: 1 / 3;
        justify-self: center;
        width: 400px;
      }
    }
    
    @media (max-width: 810px) {
      .wrapper {
        grid-template-columns: repeat(1, 400px);
      }
    
       /* RESET */
      .box:last-child {
        grid-column: auto;
        justify-self: stretch;
        width: auto;
      }
    }
    
    @media (max-width: 400px) {
      .wrapper {
        grid-template-columns: repeat(1, 300px);
      }
    }
    
    .box {
      background-color: red;
    }
    <div class="block bg-success">
      <h1>Projects</h1>
      <div class="wrapper">
        <div class="box">A</div>
        <div class="box">B</div>
        <div class="box">C</div>
      </div>
    </div>