Mystic Mickey
Mystic Mickey

Reputation: 240

How do I add background image in streamlit?

Currently I am using streamlit version 1.9.0. I am facing difficulty while adding background image to my streamlit app. I tried the following code snippet, but the image cannot be seen in the background.

import base64
import streamlit as st


def get_base64(bin_file):
    with open(bin_file, 'rb') as f:
        data = f.read()
    return base64.b64encode(data).decode()


def set_background(png_file):
    bin_str = get_base64(png_file)
    page_bg_img = '''
    <style>
    body {
    background-image: url("data:image/png;base64,%s");
    background-size: cover;
    }
    </style>
    ''' % bin_str
    st.markdown(page_bg_img, unsafe_allow_html=True)

set_background('./images/background.png')

Upvotes: 3

Views: 12840

Answers (1)

axsyse
axsyse

Reputation: 98

This is because of how Streamlit lays out the page. In Streamlit, the "body" element seems to be a div of class stApp. So, try switching your style block to use .stApp instead of body:

def set_background(png_file):
    bin_str = get_base64(png_file)
    page_bg_img = '''
    <style>
    .stApp {
    background-image: url("data:image/png;base64,%s");
    background-size: cover;
    }
    </style>
    ''' % bin_str
    st.markdown(page_bg_img, unsafe_allow_html=True)

Upvotes: 5

Related Questions