如何让容器内数据不溢出且保留原有CSS样式?
解决容器内文本超出宽度的问题
需求:让容器内所有数据在容器宽度范围内显示,同时保留现有CSS样式,当前“big word here”内容超出容器宽度。
原代码
HTML
<div class="container"> <p class ="collapse">data1 <span class ="DataRightAlign"> small </span ></p> <p class ="collapse">data2 <span class ="DataRightAlign"> small</span></p> <p class ="collapse">data3 <span class ="DataRightAlign"> big word here</span></p> </div >
CSS
.container{ width: 110px; border-style: ridge; } .collapse { display: flex !important; align-items: flex-end !important; } .collapse:after { content: '' !important; flex: auto !important; min-width: 24px !important; margin: 0 6px !important; height: 2px !important; color: lightgrey !important; font-weight: 900 !important; margin-bottom: 4px !important; background-image: linear-gradient(to right,currentColor 2px,transparent 1px) !important; background-size: 4px 2px !important; } .DataRightAlign { flex: none; } .DataRightAlign:last-child { order: 1; text-align: right; }
解决方案
问题核心在于右侧的.DataRightAlign元素设置了flex: none,无法自动收缩,且未配置文本换行规则,导致长文本超出容器。只需修改.DataRightAlign的样式即可解决:
.DataRightAlign { flex: 0 1 auto; /* 允许元素缩小,避免超出容器 */ word-wrap: break-word; /* 强制长文本换行 */ overflow-wrap: break-word; max-width: calc(100% - 60px); /* 预留左侧文本和虚线分隔符的空间 */ }
修改后,长文本会自动换行,同时保留原有虚线分隔、左右对齐的样式,所有内容都能在容器宽度范围内显示。
内容的提问来源于stack exchange,提问作者Sarahrb
相关产品推荐
相关产品推荐

