😍 Adding an icon to a st.metric easily

Hi,
This is a simple code I use in my dashboards for adding an icon to the st.metric component. These are some things you must have in mind:

This is the code

def iconMetricContainer(key,iconUnicode,color='grey'):
    """Function that returns a CSS styled container for adding a Material Icon to a Streamlit st.metric value

    Args:
        key (str): Unique key for the component
        iconUnicode (str): Code point for a Material Icon, you can find them here https://fonts.google.com/icons. Sample \e8b6 
        color (str, optional): HTML Hex color value for the icon. Defaults to 'grey'.

    Returns:
        DeltaGenerator: A container object. Elements can be added to this container using either the 'with'
        notation or by calling methods directly on the returned object.
    """
    css_style=f'''                 
                    div[data-testid="stMetricValue"]>div::before
                    {{                            
                        font-family: "Material Icons";
                        content: "{iconUnicode}";
                        vertical-align: -20%;
                        color: {color};
                    }}                    
                    '''
    iconMetric=stylable_container(
                key=key,
                css_styles=css_style
            )
    return iconMetric

And this is how you can use it:

with utils.iconMetricContainer('metricMujeres','\e13e','#FF90BC'):
    st.metric(f'Mujeres','11.4%','-0.36% - Oct 31 2023',delta_color='inverse')

And this is the result:
yyejs1sH6T

I hope this helps you to give a better look to your dashboards, you can see how it looks in this dashboard

Please let me know if you have any questions, suggestions or corrections.

Thank you

1 Like

Hi @germancastano

Amazing! This is a great code snippet for adding icons to st.metrics, thanks for sharing!

1 Like

Hi @germancastano, just FYI - there’s an old post that shows another way you can create custom metrics (with icons), in case you are interested.

Style Column Metrics like the Documentation - :balloon: Using Streamlit - Streamlit

Cheers

1 Like

Thank you, I didn’t know this post, I’ll check it, awesome alternative, I think it would be great that Streamlit components allow adding CSS classes natively as a parameter so we could handle everything using only CSS.

Thanks for sharing