繁体   English   中英

为什么内容在flexbox中溢出?

[英]Why is content overflowing in flexbox?

我遇到了一些我不理解的行为。 当我设置列表中具有最大高度和列表项上的边距的徽章列表时,列表项的内容会按比例溢出其容器。

 .badgers { display: flex; flex-direction: column; max-height: 10em; overflow: auto; border: 1px dashed red; } .badge, .title, .location, .timestamp { display: flex; } .badge { flex-direction: column; border: 1px solid black; margin: 1em 0; } 
 <div class="badgers"> <div class="badge"> <span class="title">Title</span> <span class="location">Location</span> <span class="timestamp">Timestamp</span> </div> <div class="badge"> <span class="title">Title 2</span> <span class="location">Location</span> <span class="timestamp">Timestamp</span> </div> <div class="badge"> <span class="title">Title 3</span> <span class="location">Location</span> <span class="timestamp">Timestamp</span> </div> </div> 

如果我删除边距,则没有溢出。

 .badgers { display: flex; flex-direction: column; max-height: 10em; overflow: auto; border: 1px dashed red; } .badge, .title, .location, .timestamp { display: flex; } .badge { flex-direction: column; border: 1px solid black; } 
 <div class="badgers"> <div class="badge"> <span class="title">Title</span> <span class="location">Location</span> <span class="timestamp">Timestamp</span> </div> <div class="badge"> <span class="title">Title 2</span> <span class="location">Location</span> <span class="timestamp">Timestamp</span> </div> <div class="badge"> <span class="title">Title 3</span> <span class="location">Location</span> <span class="timestamp">Timestamp</span> </div> </div> 

如果我将包装器更改为display: block并保留边距,那么列表看起来就像我想要的那样。

 .badgers { max-height: 10em; overflow: auto; border: 1px dashed red; } .badge, .title, .location, .timestamp { display: flex; } .badge { flex-direction: column; border: 1px solid black; margin: 1em 0; } 
 <div class="badgers"> <div class="badge"> <span class="title">Title</span> <span class="location">Location</span> <span class="timestamp">Timestamp</span> </div> <div class="badge"> <span class="title">Title 2</span> <span class="location">Location</span> <span class="timestamp">Timestamp</span> </div> <div class="badge"> <span class="title">Title 3</span> <span class="location">Location</span> <span class="timestamp">Timestamp</span> </div> </div> 

那么为什么display: flex; flex-direction: column列表时内容会溢出display: flex; flex-direction: column display: flex; flex-direction: column但不display: block

默认情况下,flex项目设置为flex-shrink: 1 )。

这意味着它们可以缩小以避免容器溢出。

禁用此功能。 使flex项目flex-shrink: 0


更新 (根据评论):

  • 它在Firefox中不起作用。

    实际上,上述解决方案已在Chrome,Firefox和Edge中进行了测试。 它有效( 小提琴演示 )。

  • flex-shrink: 0被删除时,它仍可在Firefox中使用。

    这是因为在Firefox中有另一个默认设置: min-height: auto 这意味着弹性项目不能缩小到其内容的高度以下。 Chrome会对此进行“干预”,这会覆盖规范设置。

    有关完整说明,请参阅此文章: 为什么Flex项目不会缩小内容大小?

    flex-shrink: 0方法是一种可靠的跨浏览器解决方案。

  • 最后一个项目的边距折叠。

    这可能是因为包含块“过度约束”。

    有关完整说明和解决方案,请参阅此文章: Flexbox中的上一个边距/填充折叠

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM