Search code examples
streamlit

Identify Dark theme in component.html() code


Text with color style in component.html() is not seen in Dark Theme. Is it possible to identify the theme changes in the code and accordingly set the color of the text in component.html()?

Sample code:

import streamlit.components.v1 as components

components.html(
    '<html><body> \
        <div style="color: rgb(81, 0, 12); font-size: 23px; font-family: "Book Antiqua";"> \
            "This is a test message." \
        </div> \
    </body></html>'
)

Solution

  • Detecting the theme's base at runtime is not supported yet (see GH5009).

    For now, a workaround would be to use st-theme (pip install st-theme) this way :

    import streamlit as st
    import streamlit.components.v1 as components
    from streamlit_theme import st_theme
    
    theme = st_theme()["base"] # either 'light' or 'dark'
    
    tcolor = "rgb(81, 0, 12)" if theme == "light" else "rgb(255, 255, 255)"
    
    components.html(
        f"""
    <html>
       <body>
          <div style="color: {tcolor}; font-size: 23px; font-family: "Book Antiqua";">
          "This is a test message."
          </div>
       </body>
    </html>
    """
    )
    

    enter image description here