【问题标题】:Change justify-content value when flex items overflow container当弹性项目溢出容器时更改 justify-content 值
【发布时间】:2016-03-15 01:32:16
【问题描述】:

看看下面的小提琴https://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。让它只溢出到容器的右侧?

【问题讨论】:

  • 不......坦率地说,没有任何方法(使用或不使用 flexbox)来做到这一点。 CSS 无法检测到这样的溢出。也许你可以用一个额外的包装做点什么,但它会很时髦
  • 是的,我知道没有直接的方法可以做到这一点。如果不需要 flexbox,解决它的一种方法是使用 inline-blocks 和 text-align: center on the container,但是我想为 flexbox 解决这个问题。

标签: css flexbox


【解决方案1】:

justify-content 不是正确的居中方法,因为您描述的问题。

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

在通过justify-contentalign-self 对齐之前, 任何正的可用空间都分配到自动边距 维度。

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

溢出框会忽略它们的自动边距并在end 中溢出 方向。

例如,您可以将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>

【讨论】:

  • 谢谢。请注意,为了防止奇怪的溢出,max-width: 100% 等可能有用
  • @JosephMerdrignac 是的
  • 这个例子不显示它不是在窄版本中居中吗?当内部元素比外部元素宽时,有没有办法将它们居中?
  • 如果父级没有宽度怎么办?
猜你喜欢
  • 2016-07-13
  • 2014-08-09
  • 2021-01-23
  • 2017-05-08
  • 1970-01-01
  • 2016-05-02
  • 2017-06-21
  • 2017-01-26
相关资源
最近更新 更多