Search code examples
csscss-grid

CSS Grid container shrink to items size


I'm trying to get a grid container to not be wider than the width of it's rows, i.e. fit as many columns as it can, and then collapse to the width of it's children.

For example, if the total amount of grid items are 16, the total amount of space the container has is 45px, and each grid item is 10px wide, then the desired outcome is a 4 by 4 grid wide 40px (not 45px).

I tried to set the display to inline-grid but that makes auto-fill give just one column.

.outer {
  width: 280px; /* this varies */
  background: orange;
  resize: both;
  overflow: auto;
  height: 300px;
  padding: 10px;
}
.items {
  background: green;
  display: grid;
  grid-template-columns: repeat(auto-fill, 50px);
  justify-content: end;
  column-gap: 10px;
  row-gap: 10px;
}
.item {
  height: 50px;
  width: 50px;
  background: blue;
}
<div class="outer">
  <div class="items">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div>

enter image description here

The space in this image should not be part of the grid container.


Solution

  • Consider its parent to be a grid container where you apply the same rules to limit the width of your grid:

    .outer {
      width: 280px; /* this varies */
      background: orange;
      resize: both;
      overflow: auto;
      height: 300px;
      padding: 10px;
      /* added */
      display:grid;
      grid-template-columns: repeat(auto-fill, 50px);
      justify-content: end;
      column-gap: 10px;
      /**/
    }
    .items {
      grid-column:1/-1; /* take all the columns */
      background: green;
      display: grid; /* you can use "inherit" here */
      grid-template-columns: repeat(auto-fill, 50px); /* you can use "inherit" here */
      column-gap: 10px; /* you can use "inherit" here */
      row-gap: 10px;
    }
    .item {
      height: 50px;
      width: 50px;
      background: blue;
    }
    <div class="outer">
      <div class="items">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
      </div>
    </div>