You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Streamlit中带Delta与无Delta的Metric组件垂直对齐问题问询

解决Streamlit中带Delta和不带Delta的Metric组件垂直空间错位问题

在Streamlit开发场景中,当部分列的st.metric组件带有Delta值,另一部分列的st.metric不设置Delta值时,会出现组件垂直高度不一致的情况,进而导致后续所有组件(比如示例中的水平线)错位。

问题复现代码

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("------------------------")

解决方案

方法1:给无Delta的Metric添加空占位符

给不需要显示Delta的st.metric设置delta=" "(一个空格),让组件结构保持一致,从而占据相同垂直空间:

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("------------------------")

方法2:用自定义CSS强制统一Metric高度

通过注入自定义CSS,强制所有stMetric组件保持相同的最小高度,从样式层面解决错位问题:

import streamlit as st

# 注入自定义CSS
st.markdown("""
<style>
div[data-testid="stMetric"] {
    min-height: 80px; /* 可根据实际显示效果调整高度值 */
}
</style>
""", unsafe_allow_html=True)

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("------------------------")

方法3:用容器固定高度

使用st.container并设置固定高度,将Metric组件放入容器中,确保每个容器高度一致:

import streamlit as st

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

内容的提问来源于stack exchange,提问作者JPtheK9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 06:27:22