HTML:
<div id="container">
<div class="item">Foo</div>
<div class="item">Bar</div>
</div>
CSS:
#container {
display: flex;
justify-content: center;
overflow: auto;
}
.item {
flex-grow: 1;
min-width: 200px;
max-width: 300px;
}
当上述容器缩小到小于 400px 时,按预期出现水平滚动条。但是,即使一直滚动到左侧,第一项也会被容器的左边缘部分遮挡。随着容器缩小,更多的元素被遮盖。
演示:http://jsfiddle.net/FTKcQ/ .调整结果框的大小以进行观察。在 Chrome 30 和 Firefox 24 中测试。
如果 justify-content
从 center
更改为任何其他值(例如 space-between
),则所有内容都可见滚动。为什么居中元素的行为不同?
这里的目标是有一排居中的元素,每个元素的宽度都会在一定范围内增加。如果容器无法容纳所有最小宽度的元素,它应该滚动以显示所有元素。
根据 MDN (Flex item considerations) ,目前预计会出现这种行为:
Flexbox's alignment properties do "true" centering, unlike other centering methods in CSS. This means that the flex items will stay centered, even if they overflow the flex container. This can sometimes be problematic, however, if they overflow past the top edge of the page, or the left edge, as you can't scroll to that area, even if there is content there! In a future release, the alignment properties will be extended to have a "safe" option as well.
For now, if this is a concern, you can instead use margins to achieve centering, as they'll respond in a "safe" way and stop centering if they overflow. Instead of using the align- properties, just put auto margins on the flex items you wish to center. Instead of the justify- properties, put auto margins on the outside edges of the first and last flex items in the flex container.
因此,您可以使用边距进行对齐来达到预期的效果。只需为第一项添加 margin-left: auto
,为最后一项添加 margin-right:auto
。
我的演示:http://jsfiddle.net/WFxQk/