1

I have a list of boxes on a page and I want to be able to configure them to wrap when there is not enough space on the screen.

Right now, when the boxes wraps, it leaves an empty space on the right side similar to this.

enter image description here

I would like the remove the extra (blue) empty space on the right side, either by tighten the blue container so that it leaves no space on each side or center the pink boxes like below.

enter image description here

There are couple requirements. 1. The blue container's width is decided by its parent. So it should grow and shrink as the parent's size changes, ie. the container shouldn't be fixed width. 2. The number of pink boxes is arbitrary, the point is really to wrap without space. 3. Done in CSS if possible. (I don't know if it can be done in CSS only)

I have tried flex and simply inline-block, but none worked out so far. I really want to know how I can do it in CSS only if possible.

My code

html, body {
  height: 100%;
}
div {
  outline: 1px solid black;
}

.track {
  margin: 10px auto;
  background: lightblue;
  display: inline-block;
  width: auto;
  height: fit-content;
}

.item {
  display: inline-block;
  background: lightpink;
  height: 250px;
  width: 250px;
  margin: 10px;
  margin-right: 0;
}
  <div class="track">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
  </div>
 
louis.luo
  • 2,921
  • 4
  • 28
  • 46
  • Also https://stackoverflow.com/questions/42176419/targeting-flex-items-on-the-last-or-specific-row – Paulie_D Feb 05 '20 at 23:02
  • It's not exactly what you're looking for, but perhaps `justify-content: space-between` is acceptable? [Codepen here](https://codepen.io/Soleil167/pen/MWwWejG) – Benjamin Feb 05 '20 at 23:42
  • @Benjamin Thanks for the suggestion. Thought about `space-between`, but didn't want the extra gap in between items either. – louis.luo Feb 06 '20 at 17:02

0 Answers0