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

如何调整ListItem宽度适配ListItemText以实现聊天气泡效果?

问题描述

聊天气泡布局问题

希望将红色边框标记的白色容器宽度调整为ListItemText中primary内Typography文本的宽度,以此模拟聊天气泡效果。曾尝试通过检查CSS解决,但未成功,请问该如何实现?

当前代码

<ListItem
  sx={{
    textAlign: "left",
    bgcolor: "#f6f6f6",
    borderRadius: "10px",
    marginBottom: "1rem",
  }}
>
  <ListItemText
    sx={{ textAlign: "right" }}
    primary={
      <React.Fragment>
        <Typography sx={{ textAlign: "right" }} color="text.primary">
          {" "}
          {" Lorem ipsum dolor sit amet"}
        </Typography>
      </React.Fragment>
    }
    secondary={
      <React.Fragment>
        <Typography
          sx={{
            fontWeight: "bold",
            fontSize: "12px",
            textAlign: "right",
            marginTop: 1,
          }}
          color="text.primary"
        >
          {" "}
          {"22:44"}
        </Typography>
      </React.Fragment>
    }
  />
  <ListItemAvatar sx={{ ml: 2, textAlign: "right" }}>
    <Avatar alt="Remy Sharp" src={w1} />
  </ListItemAvatar>
</ListItem>
解决方案

要实现聊天气泡宽度贴合文本内容,核心是打破Material-UI组件默认的全屏块级布局,让容器收缩适配内容,具体修改如下:

  • 调整ListItem的布局行为:将其改为行内块元素并靠右浮动,避免占满整行

    <ListItem
      sx={{
        display: "inline-block",
        float: "right",
        clear: "both",
        textAlign: "left",
        bgcolor: "#f6f6f6",
        borderRadius: "10px",
        marginBottom: "1rem",
        padding: "0.5rem", // 可选:增加内边距让气泡更美观
      }}
    >
    
  • 取消ListItemText的强制宽度:移除默认的flex: 1属性,让它仅占自身内容宽度

    <ListItemText
      sx={{
        textAlign: "right",
        flex: "none",
      }}
    >
    
  • 优化文本容器样式(可选):给primary内的Typography添加内边距,让气泡内的文本更舒适

    <Typography
      sx={{
        textAlign: "right",
        padding: "0.3rem 0.8rem",
      }}
      color="text.primary"
    >
      {" Lorem ipsum dolor sit amet"}
    </Typography>
    

修改后,白色容器会自动收缩到文本的实际宽度,完全匹配聊天气泡的视觉效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:06:55