Streamlit聊天机器人样式问题:row-reverse下文本对齐及尺寸调整
问题描述
我用Python和Streamlit开发聊天机器人,想要实现用户消息显示在右侧、机器人消息显示在左侧的布局。尝试用带row-reverse的CSS配置,但文本大小和聊天消息尺寸不符合预期。
现有CSS代码:
用户消息样式:
div.stChatMessage.st-emotion-cache-1c7y2kd.eeusbqq4 { width: 350px; display: flex; flex-direction: row-reverse; align-items: flex-start; justify-content: flex-end; }
机器人消息样式(背景高亮):
div.stChatMessage.st-emotion-cache-4oy321.eeusbqq4 { background-color: hsla(208, 29%, 78%, 0.66); border: 1px solid transparent; width: 550px; border-radius: 25px; }
复现代码参考Streamlit官方文档「Build a ChatGPT-like app」部分,当前效果如图:
期望实现类似此图的布局:
解决方案
你之前的问题核心在于依赖了Streamlit动态生成的st-emotion-cache-xxx类名,这类名称会随版本更新或样式变化失效;同时固定宽度、未统一文本样式也导致布局不符合预期。下面是更稳定且贴合需求的CSS配置:
/* 全局调整聊天消息容器基础样式 */ div.stChatMessage { max-width: 80%; /* 限制消息最大宽度,避免过宽 */ padding: 10px 15px; margin: 8px 0; border-radius: 20px; font-size: 14px; /* 统一文本大小 */ line-height: 1.5; /* 优化行高,提升可读性 */ } /* 用户消息:右对齐+专属背景色 */ div[data-testid="stChatMessage-user"] { margin-left: auto; /* 自动左外边距实现右对齐 */ background-color: #007bff; /* 可自定义用户消息背景色 */ color: white; /* 用户消息文本色 */ } /* 机器人(助手)消息:左对齐+高亮背景 */ div[data-testid="stChatMessage-assistant"] { margin-right: auto; /* 自动右外边距实现左对齐 */ background-color: hsla(208, 29%, 78%, 0.66); /* 保留你原来的背景色 */ color: #333; /* 机器人消息文本色 */ } /* 调整用户消息的头像位置,符合常规聊天界面逻辑 */ div[data-testid="stChatMessage-user"] > div:first-child { order: 2; /* 把用户头像放到消息右侧 */ margin-left: 10px; } div[data-testid="stChatMessage-user"] > div:last-child { order: 1; /* 把用户消息内容放到左侧 */ } /* 机器人头像与内容的间距调整 */ div[data-testid="stChatMessage-assistant"] > div:first-child { margin-right: 10px; }
使用示例
把上述CSS通过st.markdown嵌入到你的Streamlit代码中,示例如下:
import streamlit as st # 注入自定义CSS st.markdown(""" <style> /* 粘贴上面的CSS代码 */ </style> """, unsafe_allow_html=True) # 聊天逻辑参考官方文档实现 if "messages" not in st.session_state: st.session_state.messages = [] for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) if prompt := st.chat_input("输入你的问题..."): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) # 机器人回复逻辑(这里用模拟回复示例) response = f"收到你的消息:{prompt}" st.session_state.messages.append({"role": "assistant", "content": response}) with st.chat_message("assistant"): st.markdown(response)
关键优化点
- 用
data-testid属性定位消息,替代不稳定的动态类名,避免样式失效 - 通过
margin-left: auto/margin-right: auto实现消息左右对齐,替代固定宽度,适配不同屏幕 - 统一文本大小和行高,提升整体可读性
- 调整用户消息的头像位置,贴合主流聊天界面的布局习惯
内容的提问来源于stack exchange,提问作者Murphy
相关产品推荐
相关产品推荐

