如何减少Streamlit中两个multiselect组件的垂直空白
问题解决:Streamlit Multiselect组件间多余垂直空白消除
问题根源
你循环调用st.markdown注入CSS样式时,每一次调用都会让Streamlit渲染一个隐藏的markdown容器,这些容器会占据垂直空间,最终导致两个Multiselect组件之间出现多余空白。
修复代码
把所有标签的样式合并到**单个st.markdown**中,避免多次调用产生额外容器:
import streamlit as st st.set_page_config(layout="wide", page_title="Police Report Triaging") st.subheader("Key information") col3, col4 = st.columns([0.5,2.5]) person_list = ['Victim','Accused','Suspect','Witness'] # 合并所有样式到一个markdown调用里,消除多余容器 style_content = "<style>" for person in person_list: style_content += f""" span[data-baseweb="tag"]:has(span[title="{person}"]) {{ background-color: #1E90FF !important; }} """ style_content += "</style>" st.markdown(style_content, unsafe_allow_html=True) with col3: st.multiselect( label="Person", default = ["Victim"], options= person_list ) with col4: st.markdown('#') st.write("**Name**: Samuel") col5, col6 = st.columns([0.5,2.5]) with col5: st.multiselect( label="Person", default = ["Accused"], options= person_list ) with col6: st.markdown('#') st.write("**Name**: Bob")
可选优化
如果还有细微空白残留,可以添加CSS移除markdown容器的默认边距:
/* 追加到上面的style_content里 */ .stMarkdown { margin: 0 !important; }
内容的提问来源于stack exchange,提问作者user13540211
相关产品推荐
相关产品推荐

