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

如何为聊天框添加条件CSS实现消息宽度适配对齐?

聊天框消息自适应对齐实现方案

需求说明

开发聊天框时的消息对齐需求:

  • 当用户(ch1)发送的消息宽度未占满聊天框全宽时,消息自动右对齐;
  • 当消息内容过长占满全宽时,保持margin-left:30px的间距,保证整体设计一致性。

初始代码

.transcription-texts {
  height: 70vh;
  padding: 20px;
  padding-right: 0px;
  overflow: auto;
  direction: rtl;

  .speaker-turn {
    display: flex;
    gap: 10px;
    align-items: flex-start;
    direction: ltr;

    .speaker-font {
      color: white;
      margin-bottom: 20px;
      padding: 10px 30px 10px 10px;

      &.ch1 {
        margin-left: auto; // 这里需要在消息占满全宽时改为margin-left:30px
        background-color: #68a4ff;
        border-radius: 20px;
        border-top-right-radius: 0px;
      }
      &.ch2 {
        background-color: #0041a4;
        border-radius: 20px;
        border-top-left-radius: 0px;
        margin-right: 30px;
      }
    }
  }
}

聊天框界面示例

解决方案

React渲染代码片段

if (each.ch === "ch1") {
  return (
    <div className={`speaker-turn customer`}>
      <span className="speaker-font ch1">{each.t}</span>
      <img src={CustomerIcon} />
    </div>
  );
} else if (each.ch === "ch2") {
  return (
    <div className={`speaker-turn`}>
      <img src={AgentIconDark} />
      <span className="speaker-font ch2">{each.t}</span>
    </div>
  );
}

调整后的SCSS代码

.transcription-texts {
  height: 70vh;
  padding: 20px;
  padding-right: 0px;
  overflow: auto;
  direction: rtl;

  .speaker-turn {
    display: flex;
    gap: 10px;
    align-items: flex-start;
    direction: ltr;

    &.customer {
      justify-content: end;
    }

    .speaker-font {
      color: white;
      margin-bottom: 20px;
      padding: 10px 30px 10px 10px;

      &.ch1 {
        margin-left: 30px;
        background-color: #68a4ff;
        border-radius: 20px;
        border-top-right-radius: 0px;
      }
      &.ch2 {
        background-color: #0041a4;
        border-radius: 20px;
        border-top-left-radius: 0px;
        margin-right: 30px;
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:06:42