Search code examples
htmlcsscss-grid

Make a CSS Grid fit the minimum amount of space


I have something like this :

.row {
  width: 300px;
  border: 1px solid black;
  display: flex;
}

.otherstuff {
  flex-grow: 1;
}

.grid {
  display: grid;
  grid-auto-flow: column;
  gap: 10px 10px;
}

.cell {
  border: 1px solid blue;
}
<div class='row'>
  <div class='stuff'>Stuff</div>
  <div class='otherstuff'>
    <div class='grid'>
      <div class='cell'>Cell 1</div>
      <div class='cell'>Cell 2</div>
    </div>
  </div>
</div>

I would like the grid to take up only the minimal amount of space required, and not to stretch out. I've read this thread and saw that it was possible with grid-template-columns and auto values, but is there a way to do it without knowing the number of children in advance ?

Thank you.


Solution

  • You can use grid-auto-columns: min-content or grid-auto-columns: max-content, this property will affect only columns with the size not set.

    The grid-auto-columns CSS property specifies the size of an implicitly-created grid column track.

    .row {
      width: 300px;
      border: 1px solid black;
      display: flex;
    }
    
    .otherstuff {
      flex-grow: 1;
    }
    
    .grid {
      display: grid;
      grid-auto-flow: column;
      gap: 10px 10px;
      grid-auto-columns: max-content;
    }
    
    .cell {
      border: 1px solid blue;
    }
    <div class='row'>
      <div class='stuff'>Stuff</div>
      <div class='otherstuff'>
        <div class='grid'>
          <div class='cell'>Cell 1</div>
          <div class='cell'>Cell 2</div>
        </div>
      </div>
    </div>