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

white-space与text-overflow结合时CSS Transition hover失效问题

解决white-space切换时过渡不生效的问题

嘿,我来帮你搞定这个过渡失效的问题!你遇到的情况其实是CSS过渡的一个常见限制:只有可插值的数值型属性(比如width、height、opacity、max-height这些)才能触发平滑过渡,而white-space属于离散型属性(只有nowrap、normal这类固定枚举值),浏览器没法在这两个值之间生成中间状态,所以你设置的transition自然就不起作用啦。

不过别担心,我们可以用一个小技巧来模拟出平滑展开的效果——借助max-height属性来实现,因为它是数值型的,支持过渡。下面是修改后的代码:

修改后的CSS代码

.App p { margin-bottom: 3px; }
.App .bg-row { box-shadow: 0px 0px 5px #bdc3c7; background-color: #ecf0f1a3; padding: 20px; border-radius: 5px; }
.App .bg-row .repositorios { transition: all 0.2s ease; margin-bottom: 20px; }
.App .bg-row .repositorios:hover .repo-content { background-color: #d2d6d8; transition: 500ms ease-in-out; }
.App .bg-row .repositorios .repo-image { width: 100%; height: auto; box-shadow: 0px 0px 5px #bdc3c7; transition: all 0.2s ease; }
.App .bg-row .repositorios .repo-content { padding: 10px; transition: 500ms ease-in-out; overflow: hidden; box-shadow: 0px 0px 5px #bdc3c7; background-color: #ecf0f1; }
.App .bg-row .repositorios .repo-content .read-more { 
  cursor: pointer;
  white-space: nowrap; 
  text-overflow: ellipsis; 
  overflow: hidden;
  max-height: 1.5em; /* 初始值:等于一行文字的高度,根据你的line-height调整 */
  transition: max-height 0.5s ease-in-out; /* 给max-height加过渡 */
}
.App .bg-row .repositorios .repo-content .read-more:hover { 
  white-space: normal; 
  max-height: 10em; /* 足够大的值,确保能装下所有文本 */
}

关键修改点说明

  • 给.read-more初始状态设置max-height: 1.5em:这个值要和你的文本行高匹配(比如默认line-height是1.5的话,一行就是1.5em),这样超出一行的内容会被隐藏,配合white-space: nowrap和text-overflow: ellipsis实现省略号效果。
  • hover时修改max-height为一个足够大的数值(比如10em):同时把white-space改成normal,这样文本会自动换行,而max-height的数值变化会触发平滑过渡,模拟出文本展开的动画效果。
  • 把过渡属性明确指定为max-height:比用all更高效,也避免不必要的过渡。

这样修改后,鼠标hover文本时就能看到平滑的展开效果啦,同时也保留了你原本想要的省略号和hover展开的功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:17:19