如何在Streamlit中自定义不同tags组件的颜色?
你的CSS样式没生效主要是两个问题:选择器语法错误,以及依赖了Streamlit动态生成的不稳定类名。下面给你两种可靠的实现方式:
方式一:通过组件标签文本定位(无需修改Python结构)
Streamlit会给每个组件的容器生成包含标签文本的元素,我们可以利用这个特性精准定位不同的tags组件:
- 修正你的
style.css内容:
/* Platform标签组的样式 */ div[data-testid="stVerticalBlock"]:has(label:contains("Platform")) .stTags [data-testid="stTag"] { background-color: #007bff; /* 蓝色 */ color: #ffffff; /* 文字白色,提升可读性 */ border: none; /* 可选:去掉默认边框 */ } /* Amount标签组的样式 */ div[data-testid="stVerticalBlock"]:has(label:contains("Amount")) .stTags [data-testid="stTag"] { background-color: #9370db; /* 紫色 */ color: #ffffff; border: none; }
- 保持你原有的CSS引入代码不变,确保
style.css和主脚本在同一目录下:
with open('style.css') as f: st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
方式二:用自定义容器包裹组件(更稳定,不受标签文本变化影响)
如果后续标签文本可能修改,推荐给每个tags组件单独包裹自定义容器:
- 修改Python代码,给每个tags组件加自定义类的容器:
col7, col8 = st.columns([2.5, 2.5]) with col7: # 包裹Platform标签组的自定义容器 st.markdown('<div class="platform-tags">', unsafe_allow_html=True) platform = st_tags( value=["Carousell"], maxtags=3, suggestions=["Carousell"], label="Platform", ) st.markdown('</div>', unsafe_allow_html=True) with col8: # 包裹Amount标签组的自定义容器 st.markdown('<div class="amount-tags">', unsafe_allow_html=True) amount = st_tags( value=["500"], maxtags=3, suggestions=["500", "1000"], label="Amount", ) st.markdown('</div>', unsafe_allow_html=True)
- 对应的
style.css内容:
.platform-tags .stTags [data-testid="stTag"] { background-color: #007bff; color: #ffffff; } .amount-tags .stTags [data-testid="stTag"] { background-color: #9370db; color: #ffffff; }
关键注意事项
- 不要依赖
css-3u772n这类动态生成的类名,Streamlit版本更新时这类类名会变化,导致样式失效 - 引入CSS时确保文件路径正确,若不确定可以直接把CSS代码内联到
st.markdown里,比如:st.markdown(''' <style> .platform-tags .stTags [data-testid="stTag"] { background-color: #007bff; color: #ffffff; } </style> ''', unsafe_allow_html=True)
内容的提问来源于stack exchange,提问作者user13540211
相关产品推荐
相关产品推荐

