【问题标题】:How to center the title and an image in streamlit?如何在streamlit中将标题和图像居中?
【发布时间】:2022-10-31 15:02:34
【问题描述】:

我已经为标题尝试了下面的命令,但我做不到。对于图像,我只是设法通过增加大小使其居中,使其填满整个页面。 st.title()st.image 是否有任何参数可以让我将它们居中?

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

【问题讨论】:

    标签: python css streamlit


    【解决方案1】:

    要使文本居中,您可以像这样使用降价:

    #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)
    


    或者你可以像这样使用 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(' ')
    

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

    【讨论】:

      【解决方案2】:

      使用列在中心对齐图像不会一直有效。更具体的选择是使用降价来显示图像。

      但首先必须将图像转换为 Base64。以下是对 png 图像执行此操作的解决方案。

      # Solution provided by dataprofessor (https://discuss.streamlit.io/t/image-in-markdown/13274/10) modified by mze3e to center the image
      # img_to_bytes and img_to_html inspired from https://pmbaumgartner.github.io/streamlitopedia/sizing-and-images.html
      
      import base64
      from pathlib import Path
      from utilities import load_bootstrap
      
      def img_to_bytes(img_path):
          img_bytes = Path(img_path).read_bytes()
          encoded = base64.b64encode(img_bytes).decode()
          return encoded
      def img_to_html(img_path):
          img_html = "<img src='data:image/png;base64,{}' class='img-fluid'>".format(
            img_to_bytes(img_path)
          )
          return img_html
      
      st.markdown(<p style='text-align: center; color: grey;'>"+img_to_html('image.png')+"</p>", unsafe_allow_html=True)
      

      【讨论】:

        猜你喜欢
        • 2013-12-07
        • 2017-07-31
        • 1970-01-01
        • 2015-02-19
        • 2013-12-14
        • 2011-04-24
        • 2017-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多