css - 滚动的 flex 容器不适合居中的元素

标签 css flexbox

<分区>

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-contentcenter 更改为任何其他值(例如 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/

关于css - 滚动的 flex 容器不适合居中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19599431/

相关文章:

css - 外部元件间距

html - Bootstrap如何垂直居中

jquery - 表头最大高度,不够横向展开

html - 是否可以在不使用绝对位置的情况下进行以下布局

html - 使用 flexbox 和伪元素构建 line-through 样式

html - 父 div 的高度百分比未转换为子 div 的百分比

css - Twitter Bootstrap - 带行跨度的表 strip 化

javascript - 背景三 Angular 形代替圆形JS

css - flex : 0, 上的转换有问题但仍在 flex : . 0001 上工作?

javascript - 根据相邻元素的大小或值隐藏 flexbox 元素