Search code examples
csscss-grid

Justifying column(s) in CSS Grid defined with repeat()


I have a multiple column CSS Grid defined with repeat(6, 1fr) but with only one or two columns defined. It seems justifying center or space-between does not work in this case, probably because the grid already knows it has 6 equal width columns so there is nothing to justify?

.grid {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    grid-template-rows: 3em;
    grid-gap: 1rem;
    /*justify-items: center; horizontally centers column content */
    /*align-items: center; vertically centers column content */
}

.grid > div {
  background-color: yellow;
}

.grid > div:first-child {
  background-color: orange;
}
<div class="grid">
   <div>content1</div>
   <div>content2</div>
</div>


Solution

  • If you will have only one row you can do the following otherwise use flexbox:

    .grid {
      display: grid;
      grid-auto-columns: calc((100% - 5rem)/6); 
      grid-auto-flow: column;
      grid-template-rows: 3em;
      grid-gap: 1rem;
      justify-content: center;
      border: 1px solid;
    }
    
    .grid>div {
      background-color: yellow;
    }
    
    .grid>div:first-child {
      background-color: orange;
    }
    <div class="grid">
      <div>content1</div>
      <div>content2</div>
    </div>
    
    <div class="grid">
      <div>content1</div>
      <div>content2</div>
      <div>content3</div>
    </div>
    
    <div class="grid" style="justify-content: space-between;">
      <div>content1</div>
      <div>content2</div>
    </div>
    
    <div class="grid" style="justify-content: space-between;">
      <div>content1</div>
      <div>content2</div>
      <div>content3</div>
    </div>