Search code examples
csscss-grid

Center The Leftover Item From The Last Row In GRID (1fr 1fr)


This is something that I've been struggling with for a while, but I can't seem to find a way to do it.

If you have an odd number of items in grid and you want 2 items per row (1fr 1fr), you end up with a single item in the last row that is left-centered. I just want to make it centered so it looks nicer.

Here's a picture too.


Solution

  • You can try something like this jsfiddle:

    /* visibility properties */
    body {
      width: 60%;
      margin: 5% auto;
    }
    div {
      margin: 3%;
      width: 100px;
      height: 100px;
      background-color: black;
      justify-self: center;
    }
    div:nth-of-type(2n) {
      background-color: red;
    }
    
    /* actual code: */
    section {
      display: grid;
      grid-template-columns: 1fr 1fr;
    }
    
    #last-div {
      grid-column: 1 / span 2;
    }
    <section>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div id="last-div">
    </div>
    </section>

    Get more info on CSS Grid: complete-guide-grid