当 flex 项目溢出容器时更改 justify-content 值

Change justify-content value when flex items overflow container

看下面fiddlehttps://jsfiddle.net/27x7rvx6

CSS(#test是flexbox容器,.items是它的子容器):

#test {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  width: 300px;
  margin-left: 150px;
  border: 2px solid red;  
}
.item {
  flex: 0 0 70px;
  margin-right: 10px;
  background: blue;
  height: 70px;
  border: 2px solid black;
}

有一行 (nowrap) 固定大小项目的 flexbox。容器已将 justify-content 设置为 center。因为物品不能收缩并且比容器宽,所以它们开始溢出。

我的问题是内容向左和向右溢出。有没有办法让内容对齐居中,但一旦它开始溢出,就让它表现得像 justify-content 属性 设置为 flex-start,resp。让它只溢出到容器的右侧?

由于您描述的问题,

justify-content 不是正确的居中方法。

相反,我推荐 auto margins。您可以使用它们居中:

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

它们的行为如你所愿,溢出:

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

例如,您可以将 margin-left: auto 设置为第一个弹性项目,将 margin-right: auto 设置为最后一个弹性项目,或者插入 ::before::after 伪元素。

.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>