Search code examples
htmlcssuser-interfacestreamlit

Streamlit metric alignment with delta


In Streamlit, I have a main stats column and a comparison column. The comparison column's metric component has a delta while the main one's does not. This delta misaligns all the following components in the comparison column. How do I make the delta and non-delta metrics occupy the same vertical space so that elements following the metric aren't misaligned?

Problem (note how horizontal lines are misaligned):

import streamlit as st

c1, c2, c3 = st.columns(3)
with c1:
    st.metric("Main", 1, delta=None, delta_color="normal")
    st.write("------------------------")
with c2:
    st.metric("Compare", 1, delta=1, delta_color="normal")
    st.write("------------------------")
with c3:
    st.metric("asdf", 1, delta=None, delta_color="normal")
    st.write("------------------------")

Misaligned metric components


Solution

  • You can use custom CSS to accomplish what you want:

    import streamlit as st
    
    css = """
    <style>
    div[data-testid="stMetric"] {
        min-height: 100px;
    }
    </style>
    """
    st.markdown(css, unsafe_allow_html=True)
    
    c1, c2, c3 = st.columns(3)
    
    with c1:
        st.metric("Main", 1, delta=None, delta_color="normal")
        st.markdown("---")
    with c2:
        st.metric("Compare", 1, delta=1, delta_color="normal")
        st.markdown("---")
    with c3:
        st.metric("asdf", 1, delta=None, delta_color="normal")
        st.markdown("---")
    

    It gives:

    Aligned dividers

    I set 100px for the height but you can decrease the value if you prefer a more squeezed version for instance.