使用display:flex时如何让文本超出div宽度自动换行而非溢出
flex布局连续长字符串溢出解决方案
该问题根源为无空格连续长字符串默认不会自动断行,叠加flex容器子项默认最小宽度为内容宽度的特性,最终导致溢出容器,可通过以下方案修复:
- 方案1:直接给flex容器新增断行属性
在原有#front的CSS规则中添加断行配置即可,修改后完整代码如下:
#front { position: relative; background-color: #121212; color: #e6e600; border: 3px solid #e6e600; border-radius: 10px; width: 500px; height: auto; min-height: 400px; margin: 0 auto; padding: 30px; font-weight: bold; overflow: auto; display: flex; justify-content: center; align-items: center; /* 新增断行规则 */ word-wrap: break-word; word-break: break-all; }
- 方案2:嵌套文本标签提升兼容性
如果方案1在旧版本浏览器中不生效,可以给文本包裹一层明确的子元素限制宽度,兼容性更好:
修改后的HTML代码:
<div id="front"> <span>123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890</span> </div>
新增对应的CSS规则:
#front span { max-width: 100%; word-wrap: break-word; word-break: break-all; }
内容的提问来源于stack exchange,提问作者Udo-N
相关产品推荐
相关产品推荐

