Change justify-content value when flex items overflow container

justify-content is not the right approach to center because of the problem you describe.

Instead, I recommend auto margins. You can use them to center:

Prior to alignment via justify-content and align-self,
any positive free space is distributed to auto margins in that
dimension.

And they behave as you want with overflow:

Overflowing boxes ignore their auto margins and overflow in the end
direction.

For example, you can set margin-left: auto to the first flex item and margin-right: auto to the last one, or insert ::before and ::after pseudo-elements.

.test {
  display: flex;
  flex-flow: row nowrap;
  width: 200px;
  border: 2px solid red;
  margin: 10px;
}
.wide.test {
  width: 500px;
}
.test::before, .test::after {
  content: '';  /* Insert pseudo-element */
  margin: auto; /* Make it push flex items to the center */
}
.item {
  flex: 0 0 50px;
  margin-right: 10px;
  background: blue;
  height: 50px;
  border: 2px solid black;
}
<div class="test">
  <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 class="wide test">
  <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>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)