Flex items超出Flex容器:尝试多种CSS属性无效求排查
Flex子项超出容器的问题修复
你的卡片超出Flex容器,核心原因是卡片内的<h3>设置了white-space: nowrap,这会强制标题文本不换行,直接撑大卡片宽度;同时Flex布局默认不会压缩这种不可换行的内容,所以你之前设置的flex-shrink等属性无法生效。
修复步骤:
- 给
.card添加flex: 1,让三个卡片自动平分容器宽度,同时支持收缩;可选添加overflow-y: auto,当内容过多时显示垂直滚动条避免高度溢出。 - 修改
h3的white-space属性为normal,允许文本自动换行,消除撑大容器的根源。
修改后的关键CSS代码片段:
h3 { /* 其他属性保留 */ white-space: normal; /* 替换原有的nowrap */ } .card { /* 其他属性保留 */ flex: 1; /* 新增 */ overflow-y: auto; /* 可选 */ }
完整修改后的CSS代码:
* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: sans-serif; color: #444; } h1, h2, h3 { font-weight: bold; color: #efb60cf5; text-transform: uppercase; } h2 { font-size: 40px; font-style: italic; } h3 { font-size: 30px; font-style: italic; margin-bottom: 20px; background-color: rgba(203, 203, 59, 0.066); padding: 10px 10px; white-space: normal; overflow: hidden; } p { line-height: 1.5; text-transform: capitalize; font-weight: bold; } a { color: azure; } .nav { display: flex; gap: 12px; font-size: 18px; } .main-container { width: 70%; margin: 0 auto; height: 100%; border: 5px solid black; } .header { background-color: #444; display: flex; align-items: center; justify-content: space-between; margin-bottom: 60px; padding: 30px 40px; } .article-header { white-space: nowrap; overflow: hidden; margin-bottom: 30px; padding: 15px 5px; background-color: #444; } .cards { display: flex; align-items: center; gap: 15px; margin-bottom: 30px; margin-left: 10px; margin-right: 10px; } .card { border: 2px solid black; padding: 10px 10px; height: 400px; flex: 1; overflow-y: auto; } footer { border: 5px solid black; padding: 15px 15px; }
容器显示效果截图:

内容的提问来源于stack exchange,提问作者Harsh Gaur
相关产品推荐
相关产品推荐

