Search code examples
htmlcssstreamlit

Customize color of tags in streamlit


I am new to streamlit and trying to create an application which includes multiple tags object. The tags have a preset color set to red. I would like to have different color set for each tags element I have. For eg., I want to show tags under platform in blue and the tags under amount in purple.

enter image description here

I have tried to create a style.css file and open it within my main file but it doesn't seem to get applied

div.element-container css-3u772n e1tzin5v2 {
   background-color : #50C878;
}

with open('style.css') as f:
   st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)

col7, col8= st.columns([2.5, 2.5])
with col7:
   platform = st_tags(
         value= ["Carousell"],
         maxtags=3,
         suggestions=["Carousell"],
         label="Platform",
      )

Appreciate some guidance on how to work with CSS style.


Solution

  • I did it using st.multiselect and injecting custom css on the page. If you know the options and they don't overlap between platforms and amounts, you can create a rule for each of them like I did. It checks if the span has a span child with the correct title and it colors the parent if so.

    import streamlit as st
    
    possible_platforms = ["Carousell", "Foo", "Bar"]
    possible_amounts = [">$300", "<=$300"]
    
    for pfm in possible_platforms:
        st.markdown(
            f"""
        <style>
        span[data-baseweb="tag"]:has(span[title="{pfm}"]) {{
        background-color: blue !important;
        }}
        </style>
        """,
            unsafe_allow_html=True,
        )
    
    for amount in possible_amounts:
        st.markdown(
            f"""
        <style>
        span[data-baseweb="tag"]:has(span[title="{amount}"]) {{
        background-color: purple !important;
        }}
        </style>
        """,
            unsafe_allow_html=True,
        )
    
    st.markdown("Report Category Specific Parameters")
    
    st.multiselect("Platform", possible_platforms)
    st.multiselect("Amount", possible_amounts)
    

    Platforms in Blue and amounts in purple


    Note: The has pseudo-class is supported on every browser except Firefox.