看下面的 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
andalign-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/