Search code examples
csscss-grid

CSS create grid with element take 1,5 space if container empty


I have container like this :

enter image description here

At the moment there is an empty case after element 5. So I would like to center the elements of the second line :

enter image description here

For the code i've already done :

      .country-grid
        display: grid
        grid-template-columns: repeat(auto-fill,minmax(320px, 1fr))

Solution

  • This depends on the exact use case and how many grid items you are expecting. If you know you are always going to have 5 items, you could just set a specific number of columns and offset the 4th item like so:

    .grid {
      display: grid;
      grid-template-columns: repeat(6, 1fr);
    }
    
    .grid-item {
      grid-column: span 2;
    }
    
    .grid-item:nth-child(4) {
      grid-column: 2 / span 2;
    }
    

    If the layout could have any number of items and you are looking at a more fluid approach when it comes to wrapping, then I'd suggest using flex for this as it's a lot simpler for setting up alignment like this:

    .flex {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
    }
    
    .flex-item {
      width: calc(100% / 3);
      min-width: 320px;
    }