如何在Streamlit中实现垂直滚动的元素列表?
在Streamlit中实现垂直滚动元素列表
方法一:自定义CSS + 容器实现滚动
通过注入自定义CSS样式,给容器设置固定最大高度,当内容超出时自动显示垂直滚动条。
import streamlit as st # 注入自定义滚动容器样式 st.markdown(""" <style> .scrollable-container { max-height: 400px; /* 按需调整容器最大高度 */ overflow-y: auto; padding-right: 10px; /* 防止滚动条遮挡内容 */ } </style> """, unsafe_allow_html=True) # 创建带滚动效果的容器 with st.container(): st.markdown('<div class="scrollable-container">', unsafe_allow_html=True) # 生成示例长列表 for item_idx in range(50): st.write(f"列表项 {item_idx + 1}:这是一条测试内容") st.markdown('</div>', unsafe_allow_html=True)
方法二:固定高度的可滚动列
如果需要在分栏布局中实现滚动,同样可以用CSS给目标列添加滚动样式:
import streamlit as st # 定义滚动列的CSS样式 st.markdown(""" <style> .scrollable-column { max-height: 350px; overflow-y: auto; } </style> """, unsafe_allow_html=True) # 分栏布局 left_col, right_col = st.columns(2) with left_col: st.markdown('<div class="scrollable-column">', unsafe_allow_html=True) st.subheader("可滚动内容列") for idx in range(35): st.success(f"列内条目 {idx + 1}") st.markdown('</div>', unsafe_allow_html=True) with right_col: st.subheader("普通内容列") st.write("此列内容不会触发滚动,仅展示基础内容")
关键参数说明
max-height:设置容器/列的最大可视高度,单位可以是px、vh等overflow-y: auto:当内容高度超过容器高度时,自动显示垂直滚动条;内容不足时不显示滚动条padding-right:可选,添加右侧内边距避免滚动条遮挡文字内容
内容的提问来源于stack exchange,提问作者ElVincitore
相关产品推荐
相关产品推荐

