6

I have a dynamic number of divs in a single container div with display: flex.

Now, I want my child divs to be centered, so I use justify-content: center. This works perfectly for a small number of children (the blue rectangles)

But for a larger amount of children, setting justify-content: center means that child divs are pushed farther and farther off-screen (the red rectangles).

Children pushed off-screen to the right are still visible because I can just scroll to the right to see the rightmost children.

But children pushed off-screen to the left are not visible because I cannot scroll to the left. This is a problem.

So essentially I want to use flexbox to center its children but prevent the children from being pushed off-screen to the left. Instead, content should overflow to the right, the way that justify-content: flux-start works, but still be centered.

  • 1
    Can you post some code ? – vals Jul 31 '17 at 16:05
  • I didn't want to throw this in my question at the risk of being self-promotional, but it's for a client-side Trello clone that I made: http://reacto.surge.sh. As of writing I have `justify-content` set to `flux-start`, and I've been trying to center my columns :) –  Jul 31 '17 at 16:15

1 Answers1

7

Just use nested flex-containers and set margin-left: auto and margin-right: auto for inner flex-container. This will work because auto margins work only when we have free space to distribute. Demo:

.flex {
  display: flex;
}

.inner-flex {
  display: flex;
  margin-left: auto;
  margin-right: auto;
}

/* just styles for demo */
.flex__item {
  background-color: tomato;
  color: white;
  margin: 10px;
  padding: 10px;
}
<div class="flex">
  <div class="inner-flex">
    <div class="flex__item">One</div>
    <div class="flex__item">Two</div>
    <div class="flex__item">Three</div>
    <div class="flex__item">Four</div>
    <div class="flex__item">Five</div>
    <div class="flex__item">Six</div>
    <div class="flex__item">Seven</div>
  </div>
</div>

Here is jsFiddle to test resizing.

Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90