Search code examples
cssgrid

How to Center Horizontally a Grid Item in a 2 Column Grid?


I have a grid container with 2 items in each row. The last row has only 1 item and I want it to be centered horizontally and still be as wide as all the other items. Right now, the last item is on the left.

I have tried justify-self: center; on the last item, but it doesn't work.

enter image description here

.container {
  width: 700px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  column-gap: 40px;
  row-gap: 20px;
}

.item {
  background-color: #38bdf8;
  border-radius: 16px;
  height: 50px;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>


Solution

  • I want it to be centered horizontally and still be as wide as all the other items.

    When it comes to CSS grid, you can't just center something, it has to follow the grid. You defined two columns, and so there's no middle column for the last element to occupy.

    To achieve this using CSS grid, we need to add more columns.

    .container {
      width: 700px;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      column-gap: 40px;
      row-gap: 20px;
    }
    
    .item {
      background-color: #38bdf8;
      border-radius: 16px;
      height: 50px;
      grid-column: span 2;
    }
    
    .item:last-child {
      grid-column: 2 / span 2;
    }
    <div class="container">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
    </div>