You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CSS中实现文本自动收缩?文本溢出问题求助

文本过长自动调整的解决方法

我设置文本样式时遇到问题,希望文本过长时能自动调整,试过width: fit-content但无效。以下是我的代码片段:

原JSX代码

<div className="highlights">
  <div className="highlights-text">
    <h2>{hotel.title}</h2>
    <p className="region">{hotel.region}</p>
  </div>
  <div className="highlights-price">
    <h2 className="per-night">PLN {hotel.perNight}</h2>
    <p>per night</p>
  </div>
</div>

原CSS代码

.highlights {
  align-items: flex-start;
  flex-direction: row;
  bottom: 3px;
  left: 50px;
  left: 50px;
  white-space: nowrap;
  border-radius: 8px;
  color: rgb(242, 245, 247);
  background-color: rgba(0, 0, 0, 0.8);
  opacity: 0.8;
  width: fit-content;
  text-justify: inter-word;
}
.highlights-text {
  width: 100%;
  padding: 0px 10px;
  margin: 10px 0;
  color: rgb(242, 245, 247);
  width: fit-content;
}
.highlights-price {
  padding: 0px 10px;
  margin: 10px 0;
}

解决思路与修改方案

问题核心是.highlights中的white-space: nowrap强制所有文本不换行,加上.highlights-text重复设置width导致宽度控制失效。按以下方式修改:

  • 移除.highlights里的white-space: nowrap,允许文本正常换行
  • 给.highlights-text设置max-width(比如250px,可根据布局需求调整),限制文本区域的最大宽度,超出后自动换行
  • 可选:如果希望标题过长时显示省略号,单独给标题添加省略号样式(需配合white-space: nowrap)

修改后的CSS代码

.highlights {
  align-items: flex-start;
  flex-direction: row;
  bottom: 3px;
  left: 50px;
  border-radius: 8px;
  color: rgb(242, 245, 247);
  background-color: rgba(0, 0, 0, 0.8);
  opacity: 0.8;
  width: fit-content;
}
.highlights-text {
  max-width: 250px; /* 限制文本区域最大宽度 */
  padding: 0px 10px;
  margin: 10px 0;
  color: rgb(242, 245, 247);
}
.highlights-price {
  padding: 0px 10px;
  margin: 10px 0;
}

/* 可选:标题过长显示省略号 */
.highlights-text h2 {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin: 0 0 5px 0;
}

内容的提问来源于stack exchange,提问作者Emilia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:54:57