Search code examples
htmlcsscss-grid

Centre CSS Grid Items Dependent On Dynamic Content Count


I have a series of images that are fetched from a database, and when three or more images are added it visually shows the three columns.

When less than three images are present, because I'm using display: grid; it is currently justified to the left of the parent container (in the code example I've just used red boxes to represent the images).

Is there anyway of having it so that when one or two images are present these are justified to the centre of the parent element. I appreciate I could use javascript to detect how many images are present and if it is less than three, add a class and change the wrapper to display: flex, but I wondered if such a layout was possible with CSS only?

Due to the nature of the layout I do need to use CSS Grid when more than three images are present.

Note: I've commented out two of the red boxes in the HTML to show the initial issue when only one red box is present.

Codepen: https://codepen.io/anna_paul/pen/xxXrVJQ

body {
  display: flex;
  justify-content: center;
  margin: 0
  width: 100%;
  height: 100vh;
}

.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 1rem;
  max-width: 1250px;
}

.box {
  width: 200px;
  height: 200px;
  background: red;
}
<div class="wrapper">
  <div class="box"></div>
<!--   <div class="box"></div>
  <div class="box"></div> -->
</div>


Solution

  • Do it like below:

    .wrapper {
      display: grid;
      grid-auto-flow:column; /* column flow */
      justify-content:center; /* center everything */
      grid-gap: 1rem;
      max-width: 600px;
      border:1px solid;
      margin:10px auto;
    }
    /* make sure you only have 3 columns*/
    .box:nth-child(3n + 1) {grid-column:1}
    .box:nth-child(3n + 2) {grid-column:2}
    .box:nth-child(3n + 3) {grid-column:3}
    /**/
    .box {
      width: 100px;
      height: 100px;
      background: red;
    }
    <div class="wrapper">
      <div class="box"></div>
    </div>
    <div class="wrapper">
      <div class="box"></div>
      <div class="box"></div>
    </div>
    <div class="wrapper">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>
    <div class="wrapper">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>
    <div class="wrapper">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>
    <div class="wrapper">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>