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

基于Bootstrap与Flex实现左右区分的自适应宽度聊天气泡

Bootstrap聊天气泡实现方案

刚好我之前做过类似的需求,用Bootstrap的flex布局加一点点自定义CSS就能完美实现,给你整理了完整的方案:

完整代码示例

<div class="chat-container d-flex flex-column gap-3 p-4" style="max-width: 800px; margin: 0 auto;">
  <!-- 左侧气泡(对方消息) -->
  <div class="d-flex">
    <p class="msg left px-4 py-3 rounded-3">嗨,这是一条短消息</p>
  </div>
  
  <!-- 右侧气泡(自己消息) -->
  <div class="d-flex justify-content-end">
    <p class="msg right px-4 py-3 rounded-3">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque neque est, viverra ac rhoncus et, cursus eu leo. Quisque in tristique libero, sed...</p>
  </div>
  
  <!-- 左侧长消息 -->
  <div class="d-flex">
    <p class="msg left px-4 py-3 rounded-3">这是一条比较长的测试消息,用来验证最大宽度是否生效。当文本内容超过容器的70%宽度时,气泡会自动换行,而不会撑满整个容器,短文本的时候则会自适应宽度。</p>
  </div>
</div>

<style>
.msg {
  max-width: 70%;
  width: fit-content;
  margin: 0;
}

.msg.left {
  background-color: #e9ecef;
}

.msg.right {
  background-color: #0d6efd;
  color: white;
}
</style>

关键细节拆解

  • 布局逻辑:外层用d-flex flex-column做聊天容器,gap-3添加消息间距;左侧消息用d-flex默认左对齐,右侧消息加justify-content-end实现右对齐,完全基于Bootstrap原生flex类实现
  • 宽度控制核心:max-width: 70%限制气泡最大宽度,避免长消息撑满屏幕;width: fit-content是关键,让短文本气泡只占用内容所需宽度,不会强制拉宽
  • 样式优化:用Bootstrap的rounded-3实现圆角气泡,px-4 py-3控制内边距避免文本贴边;通过.left和.right类区分气泡背景色,默认使用Bootstrap主题色和浅灰色,可按需调整

这样实现的聊天气泡完全贴合Bootstrap的设计体系,同时满足你所有的需求:左右区分、短文本自适应宽度、长消息最多占70%宽度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:27:51