1

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.

2

1 Answer 1

2

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.