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

如何在MUI的Typography组件中限制字符长度并添加省略号?

标题截断为18字符并添加省略号的两种实现方法

方法一:使用CSS文本溢出(推荐,适配响应式)

利用CSS原生属性实现自动截断,无需手动处理字符串,还能适配不同屏幕宽度:

<CardContent>
  <Typography 
    gutterBottom 
    variant="h5" 
    component="div"
    sx={{
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      maxWidth: '100%' // 可根据需求调整为固定宽度值
    }}
  >
    <Link href={`/${encodeURIComponent(data.slug)}`}>
      <a>{data.title}</a>
    </Link>
  </Typography>
</CardContent>

如果项目用className而非sx,可把样式写在CSS文件中:

.truncated-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

然后给Typography添加className="truncated-title"即可。

方法二:JavaScript手动截断字符串(精确控制字符数)

如果需要严格限制为18个字符,不管显示宽度,可写个工具函数处理标题:

// 定义截断函数
const truncateTitle = (title, maxLength) => {
  if (!title) return '';
  return title.length <= maxLength ? title : `${title.slice(0, maxLength)}...`;
};

// 组件中使用
<CardContent>
  <Typography gutterBottom variant="h5" component="div">
    <Link href={`/${encodeURIComponent(data.slug)}`}>
      <a>{truncateTitle(data.title, 18)}</a>
    </Link>
  </Typography>
</CardContent>

注意事项

  • CSS方法的whiteSpace: 'nowrap'会强制标题不换行,若需支持多行截断,可调整样式为display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical;(把1改成需要的行数),但这种方式是按行数截断,而非字符数。
  • JS方法需处理data.title为空的情况,避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:40:29