Search code examples
htmlcsscenteringcss-grid

How to perfectly center grid-items while using CSS Grid auto-fit property?


I have this Grid:

CSS Grid

You can see the full code in Codepen

The problem is that, due to auto-fit property, when changing screen size, some columns go down. I need that even if new rows appear, all the grid items should be centered in the grid container.

This is the scenario:

Scenario

body {margin: 0}

.about-us__block {
  width: 150px;
  height: 200px;
  background: yellow;
}

.about-us__container {
  background: black;
  padding: 20px 0;
  display: grid;
  justify-items: center;
  align-items: center;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  grid-gap: 10px;
}

.about-us__text {
  padding: 5px;
  text-align: center;
  background-color: #35306B;
  color: #ebecec;
}

.about-us__text h6 {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 0;
}

.about-us__text p {
  font-family: Helvetica;
  margin: 0;
}

.about-us__item:nth-of-type(4) {
  grid-column: 2;
}
<div class="about-us__container">
  <div class="about-us__item">
    <div class="about-us__block"></div>
    <div class="about-us__text">
      <h6>John Doe</h6>
      <p>BlaBla</p>
    </div>
  </div>
  <div class="about-us__item">
    <div class="about-us__block"></div>
    <div class="about-us__text">
      <h6>John Doe</h6>
      <p>BlaBla</p>
    </div>
  </div>
  <div class="about-us__item">
    <div class="about-us__block"></div>
    <div class="about-us__text">
      <h6>John Doe</h6>
      <p>BlaBla</p>
    </div>
  </div>
  <div class="about-us__item">
    <div class="about-us__block"></div>
    <div class="about-us__text">
      <h6>John Doe</h6>
      <p>BlaBla</p>
    </div>
  </div>
</div>

I'm trying a lot of solutions, but none of them works. I tried forcing the fourth grid-item to place in the 2nd column, but this occurs: .


Solution

  • I had this same layout on my project.

    On the container try:

    display: flex;
    flex-wrap: wrap;
    justify-content: center;