微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。