如何在 Streamlit 中使标题和图像居中?

Use*_*563 10 css python streamlit

我已经尝试过下面的标题命令,但失败了。对于图像,我只是通过增加尺寸使其居中,使其填充整个页面。是否有任何论据可以st.title()st.image我将它们居中?

title_alignment=
"""
<style>
#the-title {
  text-align: center
}
</style>
"""
st.markdown(title_alignment, unsafe_allow_html=True)
Run Code Online (Sandbox Code Playgroud)

Max*_*tag 16

要使文本居中,您可以使用 Markdown,如下所示:

#A streamlit app with two centered texts with different seizes
import streamlit as st

st.markdown("<h1 style='text-align: center; color: grey;'>Big headline</h1>", unsafe_allow_html=True)

st.markdown("<h2 style='text-align: center; color: black;'>Smaller headline in black </h2>", unsafe_allow_html=True)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


或者你可以使用streamlit的column关键字,如下所示:

import streamlit as st

col1, col2, col3 = st.columns(3)

with col1:
    st.write(' ')

with col2:
    st.image("https://static.streamlit.io/examples/dog.jpg")

with col3:
    st.write(' ')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这将创建您可以在其中添加文本和图像的容器。这样您就可以将图像居中。


ggo*_*len 9

这是另一种方法,稍微简化这个答案并避免使用 HTML:

import streamlit as st  # 1.18.1

with st.columns(3)[1]:
     st.header("hello world")
     st.image("http://placekitten.com/200/200")
Run Code Online (Sandbox Code Playgroud)

或者,如果您只是渲染一项:

st.columns(3)[1].header("hello world")
Run Code Online (Sandbox Code Playgroud)

不过,如果您想让文本在列中居中,HTML 似乎是唯一的方法。如果您不介意将所有<h2>s 全局居中,您可以使用:

style = "<style>h2 {text-align: center;}</style>"
st.markdown(style, unsafe_allow_html=True)
st.columns(3)[1].header("hello world")
Run Code Online (Sandbox Code Playgroud)

另请参见中心 Streamlit 按钮