Skip to content

♠️  Metric Cards

Submitted by Chanin Nantasenamat

Summary

Restyle metrics as cards

Functions

style_metric_cards

Applies a custom style to st.metrics in the page

Parameters:

Name Type Description Default
background_color str

Background color. Defaults to "#FFF".

'#FFF'
border_size_px int

Border size in pixels. Defaults to 1.

1
border_color str

Border color. Defaults to "#CCC".

'#CCC'
border_radius_px int

Border radius in pixels. Defaults to 5.

5
border_left_color str

Borfer left color. Defaults to "#9AD8E1".

'#9AD8E1'
box_shadow bool

Whether a box shadow is applied. Defaults to True.

True
Source code in src/streamlit_extras/metric_cards/__init__.py
@extra
def style_metric_cards(
    background_color: str = "#FFF",
    border_size_px: int = 1,
    border_color: str = "#CCC",
    border_radius_px: int = 5,
    border_left_color: str = "#9AD8E1",
    box_shadow: bool = True,
) -> None:
    """
    Applies a custom style to st.metrics in the page

    Args:
        background_color (str, optional): Background color. Defaults to "#FFF".
        border_size_px (int, optional): Border size in pixels. Defaults to 1.
        border_color (str, optional): Border color. Defaults to "#CCC".
        border_radius_px (int, optional): Border radius in pixels. Defaults to 5.
        border_left_color (str, optional): Borfer left color. Defaults to "#9AD8E1".
        box_shadow (bool, optional): Whether a box shadow is applied. Defaults to True.
    """

    box_shadow_str = (
        "box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15) !important;"
        if box_shadow
        else "box-shadow: none !important;"
    )
    st.markdown(
        f"""
        <style>
            div[data-testid="stMetric"],
            div[data-testid="metric-container"] {{
                background-color: {background_color};
                border: {border_size_px}px solid {border_color};
                padding: 5% 5% 5% 10%;
                border-radius: {border_radius_px}px;
                border-left: 0.5rem solid {border_left_color} !important;
                {box_shadow_str}
            }}
        </style>
        """,
        unsafe_allow_html=True,
    )

Import:

from streamlit_extras.metric_cards import style_metric_cards # (1)!
  1. You should add this to the top of your .py file πŸ› 

Examples

example

def example():
    col1, col2, col3 = st.columns(3)

    col1.metric(label="Gain", value=5000, delta=1000)
    col2.metric(label="Loss", value=5000, delta=-1000)
    col3.metric(label="No Change", value=5000, delta=0)

    style_metric_cards()
Output (beta)