0

I've set up a short demo here: codepen.io. I have a flexbox with a number of boxes in it. I've set the minimum width of the container to be 3 boxes, and the maximum to be 4. It works, but I'd like the last element to be left justified, instead of floating in the middle. Any way I can left-justify the elements and simply center the container?

CSS code for the container is here, where the width/height of one box is 100px:

.container {
  padding: 1em;
  display: flex;
  flex-wrap: wrap;
  min-width: calc(300px + 6em);
  max-width: calc(400px + 8em);
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  background: red;
}

Thanks!

Edit: The solution I'm looking for is not as simple as making the last item align to grid; more specifically, I would like the screen width to be dynamic, so the container elements are always horizontally centered and flush with their container.

  • When elements wrap, using Flexbox or not, their parent won't shrink-to-fit as it doesn't know when/if its children have wrapped. For that you need media query or script. – Asons Feb 12 '18 at 19:38
  • Is this what you look for?: https://jsfiddle.net/m1h2temj/ – Asons Feb 12 '18 at 22:20

2 Answers2

0

Use margin-right: auto; on your last item (using :last-child) to add a margin that will push your box to the left:

.container {
  padding: 1em;
  display: flex;
  overflow: auto;
  flex-wrap: wrap;
  min-width: calc(300px + 6em);
  max-width: calc(400px + 8em);
  align-items: center;
  justify-content: center;
  background: red;
}
.box {
  width: 100px;
  height: 100px;
  background: #000;
  margin: 1em;
  display: block;
}

.box:last-child { margin-right: auto; }
<h1> try resizing window</h1>
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
chriskirknielsen
  • 2,839
  • 2
  • 14
  • 24
  • Seems to stagger the bottom row when the screen width is less than that of 4 boxes – Curtis Upshall Feb 12 '18 at 18:25
  • Then I suggest you use `justify-content: flex-start;` on your `.container`, unless I don't grasp your goal fully? – chriskirknielsen Feb 12 '18 at 18:34
  • This seems to work, until the window is resized. My goal is that the boxes always be flush with the container, that the container always be horizontally centered, and that the last row be aligned with the grid, should the last row not be full. – Curtis Upshall Feb 12 '18 at 19:12
0

I changed the justify-content to "flex-start" using Chrome's "Inspect" function.

That seemed to produce the results that you want.

enter image description here

JohnH
  • 1,920
  • 4
  • 25
  • 32