css3 – 滚动弹性容器不适合居中的项目

参见英文答案 > Can’t scroll to top of flex item that is overflowing container6个
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从中心更改为任何其他值(例如,间隔),则通过滚动可以看到所有内容.为什么居中的项目表现不同?

这里的目标是有一排居中的项目,每个项目的宽度将在某个范围之间增长.如果容器无法容纳所有最小宽度的项目,则应滚动以显示所有项目.

解决方法

根据 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作为last.

我的演示:http://jsfiddle.net/WFxQk/

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效