Centring flex items and allowing overflow scroll

The problem

Centring flexbox items using justify-content results in a quriky behaviour when the content overflows the container. Even after scrolling, some items may not be fully visible.

The solution

This is a three-step solution:

  1. Don't use justify-content on the container.
  2. Add margin-left: auto; to the first child item.
  3. Add margin-right: auto; to the last child item.

Example:

<!-- HTML -->

<div class="flex-container">
    <div class="item">First item</div>
    <div class="item">Second item</div>
    <div class="item">Third item</div>
    <!-- and so on ... -->
</div>
/* CSS */

.flex-container {
    display: flex;
    flex-wrap: nowrap;
    white-space: nowrap;
    overflow-x: auto;
}

.flex-container .item:first-child {
    margin-left: auto;
}

.flex-container .item:last-child {
    margin-right: auto;
}

And the scrolling should work now.

Demo

See the Pen Overflow scroll flex centered items by Bharat Chauhan (@bhch) on CodePen.

Future solution

There's a new keyword called safe in the CSS working draft that can be used with justify-content and align-items which will allow "safe" scrolling in case the content overflows

So, you can use something like this:

.flex-container {
    justify-content: center safe;
}

And scrolling will work fine.

But currently this is only supported by Firefox (if this info has changed by the time you're reading this, please comment to let me know).