Adding my own class on components

I want to ask about styling using CSS by adding your own class to the component. Is it possible? If possible, how do I do it? Thanks

If you want to add a class to Streamlit components, you’ll have to use parent.document.querySelectorAll in st.components.v1.html to do so. You can apply CSS directly with st.markdown using unsafe_allow_html=True if you identify your elements without the need to inspect their contents.

There are a lot of CSS hacks on the forum for examples, otherwise feel free to describe your scenario specifically.

lets say i have metric1 separated by st.columns(3). and i want to created it more(metric2) with the same 3 columns. the problem is that they both have the same class.how to resolve it, iwant different class.thanks

Elements can be targeted as specifically as your JS scripts allows it. Here is an example to modify the style of metrics whose label contains the word second.

import streamlit as st

st.components.v1.html("""
    <script>
    const matches = parent.document.querySelectorAll("[data-testid='stMetricLabel']");

    matches.forEach((match) => {
        var ptag = match.getElementsByTagName("p")[0]

        // Style labels that contain the word "second"
        if (ptag.textContent.includes("second")){
            ptag.style.fontSize = "1.5rem";
            ptag.style.fontFamily = "monospace";
        }
    });
    </script>
    """, height=0, width=0)

cols = st.columns(3)

with cols[0]:
    "Style by content"

with cols[1]:
    st.metric("My first metric", 1, 0.5)

with cols[2]:
    st.metric("My second metric", 2, -0.8)

thank you, thats very helpful

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.