简体   繁体   中英

Custom color for each element in Multiselect Streamlit

Each element has a custom background color. What I want is when you click on an element, the output in the menu bar should give the same color as the element. Now it always gives the element a red color. So it is possible to change the color based on your choice of element. Here is a reproducible example:

import streamlit as st

# Styler
st.markdown(
    """
<style>
div[role="listbox"] li:nth-of-type(1){
    background-color: red;
}
div[role="listbox"] li:nth-of-type(2){
    background-color: blue;
}
</style>
""",
    unsafe_allow_html=True,
)

# multiselect
st.multiselect("Options", ["option1", "option2", "option3"])

Output open menu:

在此处输入图像描述

Output option1 :

在此处输入图像描述

Output option2 :

在此处输入图像描述

As you can see option2 is again red, but it actually should be blue.

I think this should solve your problem

st.markdown("""
<style>
    span[data-baseweb="tag"][role="button"]{
        background-color: blue;
    }
</style>

""", unsafe_allow_html=True)

Edition:

st.markdown("""
    <style>
        span[data-baseweb="tag"][aria-label="option1, close by backspace"]{
            background-color: blue;
        }
        span[data-baseweb="tag"][aria-label="option2, close by backspace"]{
            background-color: green;
        }
        span[data-baseweb="tag"][aria-label="option3, close by backspace"]{
            background-color: wheat;
        }
    </style>
    """, unsafe_allow_html=True)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM