css - 当 flex 元素溢出容器时更改 justify-content 值

标签 css flexbox

看下面的 fiddle 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。让它只溢出到容器的右侧?

最佳答案

由于您描述的问题,

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 设置为第一个 flex 元素,将 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>

关于css - 当 flex 元素溢出容器时更改 justify-content 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34184535/

相关文章:

jquery - 带有响应式导航菜单的 Chrome 错误

html - 将内联边框样式应用于表格单元格,因为里面有文本输入

css - 流体行未正确显示 bootstrap 3 + mvc 4

html - 创建可伸缩的 flex child

css - Bootstrap 网格 : Floating columns vertically

html - 如果父级在 Chrome 中有 flex-direction 列,则网格行不会拉伸(stretch)到整个元素高度

css - 当位置是相对的时,元素的填充和边距会改变吗?

CSS - 使用 SVG 掩码在 Firefox 中无法正确显示

javascript - React Native { flex : 1 } for React JS? 等价于什么

css - flexbox 可以水平和垂直居中图像而不拉伸(stretch)它们吗?