skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 1. Using an empty string for delta:

    While the delta argument is meant for displaying a change value, you can pass an empty string ("") to maintain the spacing even without a delta value. This tricks the component into reserving space for the delta, aligning the heights.

    Here’s the modified code:

    import streamlit as st
    
    c1,c2,c3 = st.columns(3)
    with c1:
        st.metric("Main",1,delta="", 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="", delta_color="normal")
        st.write("------------------------")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search