如何在Streamlit多页应用侧边栏导航上方添加Logo与标题?
如何在Streamlit多页应用的侧边栏导航上方添加Logo和标题?
我正在使用Streamlit的多页功能,想要给应用设置样式,在页面导航的上方放置Logo和标题。以下是基于Python 3.9、streamlit==1.11.1测试的示例:
目录结构
/Home.py /pages/Page_1.py /pages/Page_2.py
现有代码
Home.py
import streamlit as st st.sidebar.markdown( "My Logo (sidebar) should be on top of the Navigation within the sidebar" ) st.markdown("# Home")
Page_1.py
import streamlit as st st.markdown("Page 1")
Page_2.py
import streamlit as st st.markdown("Page 2")
运行命令
$ streamlit run Home.py
问题现象
运行后发现添加的文本显示在导航下方而非上方,效果如下:
解决方法
可以通过注入自定义CSS调整侧边栏元素的渲染顺序,将自定义内容移至导航上方,具体修改如下:
修改Home.py代码:
import streamlit as st # 注入自定义CSS调整侧边栏元素顺序 st.markdown( """ <style> /* 将自定义内容容器放在导航前面 */ [data-testid="stSidebar"] > div:first-child { order: 1; } /* 将多页导航容器放在后面 */ [data-testid="stSidebarNav"] { order: 2; } </style> """, unsafe_allow_html=True ) # 添加自定义Logo/标题内容 st.sidebar.markdown( "My Logo (sidebar) is now on top of the Navigation within the sidebar" ) st.markdown("# Home")
原理说明
Streamlit的侧边栏中,多页导航对应的DOM元素data-testid为stSidebarNav,而通过st.sidebar添加的自定义内容会放在侧边栏的第一个容器内。利用CSS的order属性,我们可以调整这两个容器的渲染顺序,让自定义内容优先显示在导航上方。
扩展说明
- 如果需要添加图片Logo,直接用
st.sidebar.image("你的logo路径.png")替代文本即可,同样会被调整到导航上方; - 该方案依赖当前版本Streamlit的DOM结构,后续版本若DOM元素标识或布局变化,可能需要对应调整CSS选择器。
内容的提问来源于stack exchange,提问作者Cord Kaldemeyer
相关产品推荐
相关产品推荐

