How to Right Justify st.chat_message?

I see that there’s no feature to right justify st.chat_message() for ‘user’ prompts. The 3rd party component, streamlit-chat, has this feature.

Is there a work-around?

1 Like

The code below should do the trick. I also found this CSS hacking tut very helpful, which should help you be able to apply this anything you want more generally.

import streamlit as st

st.markdown(
    """
<style>
    .stChatMessage {
        text-align: right;
    }
</style>
""",
    unsafe_allow_html=True,
)

with st.chat_message("user"):
    st.write("Hello 👋")
    st.write("I'm on the right 👋")
1 Like

Isn’t this CSS going to apply to all messages though, instead of just the message of role=user? I am also considering migrating from streamlit-chat to the native version, but this is a dealbreaker for me :frowning:

I believe you can target the user / system text get the emoticon used in the message. Each different emoticon

From the chatgpt text
<div class="stChatMessage st-emotion-cache-4oy321 eeusbqq4" data-testid="stChatMessage">

From my user text
<div class="stChatMessage st-emotion-cache-1c7y2kd eeusbqq4" data-testid="stChatMessage">

You can see that the emoticon class is different…

Just brainstorming. Would be better with an update to the streamlit classes to add something along the lines of “usertext” or “responsetext”.

Here’s a way to do it – NOTE that the classes involved may change, but this works today for streamlit 1.28.1 with the current classes

import streamlit as st

st.markdown(
    """
<style>
    .st-emotion-cache-janbn0 {
        flex-direction: row-reverse;
        text-align: right;
    }
</style>
""",
    unsafe_allow_html=True,
)

messages = [{
    "author": "user",
    "message": "hi",
}, {
    "author": "assistant",
    "message": "I'm a bot"
}] * 3

for message in messages:
    with st.chat_message(message["author"]):
        st.write(message["message"])

2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.