Center text in st.metric

It is really difficult to center the text in st.metric I have tried every css selector I could think of. - Anyone knows how to do it?

import streamlit as st

col_row1_1, col_row1_2, col_row1_3 = st.columns(3)
col_row1_1.metric("text1", value=3434)
col_row1_2.metric("text2", value=3434)
col_row1_3.metric("text3", value=5667567)

# css injection
def _max_width_():
    max_width_str = "max-width: 1900px;"
    st.markdown(
        f"""
    <style>
    .block-container {{
        {max_width_str}
        }}
    .css-ocqkz7 {{
        text-align: center;
        color: #23C802;
        white-space: normal;
    }}
    .css-1r6slb0.e1tzin5v2 {{
        background-color: #D2D1D1;
        border: 2px solid #A9A9A9;
        padding: 3px 3px 3px 30px;
        border-radius: 5px;
    }}
    <style>
    """,
        unsafe_allow_html=True,
    )


_max_width_()
  • Python==3.9
  • streamlit==1.11.0
import streamlit as st

col_row1_1, col_row1_2, col_row1_3 = st.columns(3)
col_row1_1.metric("text1", value=3434)
col_row1_2.metric("text2", value=3434)
col_row1_3.metric("text3", value=5667567)

st.markdown('''
<style>
/*center metric label*/
[data-testid="stMetricLabel"] > div:nth-child(1) {
    justify-content: center;
}

/*center metric value*/
[data-testid="stMetricValue"] > div:nth-child(1) {
    justify-content: center;
}
</style>
''', unsafe_allow_html=True)


Notice: when streamlit update,the css selector maybe change.

1 Like

Thanks for the quick reply :heart:
How did you find that HTML tag - I use a browser extension CSS Scan to locate selectors but I did not know that tag.

I use google browser,and press F12 to open devTools,in Elements,use Arrow to locate target elements,then analyzing web page structure, use css selector to locate target elements.
I think you may be konw more about css selector, so you can write your own css selector to locate elemetns instead of relying on tools.