Anatol Zakrividoroga
Anatol Zakrividoroga

Reputation: 4518

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>

Upvotes: 1

Views: 2688

Answers (3)

pier farrugia
pier farrugia

Reputation: 1570

if you want all items same width, and based on your actual css with container 700px and column-gap 40px, you can modify the last-child css as follow:

        .item:last-child {
            grid-column: auto / span 2;
            width: 330px;
            justify-self: center;
        }

here we give a real width at the last item equal to others

we keep the span 2 but we justify center this last item

Upvotes: 0

user7148391
user7148391

Reputation:

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>

Upvotes: 3

pier farrugia
pier farrugia

Reputation: 1570

almost there... just add span on last item

.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;
}

.item:last-child {
  grid-column: auto / span 2;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Upvotes: 0

Related Questions