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

使用pd.style无法在Streamlit中居中表格单元格内容

解决Streamlit中DataFrame单元格及表头无法居中的问题

问题核心是Streamlit的st.table()组件会通过内置CSS强制覆盖Pandas Styler设置的文本对齐样式——哪怕你在Styler里定义了text-align:center,也会被Streamlit的默认样式冲掉。

解决方案:改用HTML渲染+自定义CSS强制覆盖

放弃st.table(),改用st.markdown()渲染Pandas Styler生成的HTML,同时添加优先级更高的CSS规则来强制设置对齐:

修改后的完整代码:

import pandas as pd
import numpy as np
import streamlit as st

th_props = [
  ('font-size', '14px'),
  ('text-align', 'left'),
  ('font-weight', 'bold'),
  ('color', '#6d6d6d'),
  ('background-color', '#eeeeef'),
  ('border','1px solid #eeeeef'),
]

td_props = [
  ('font-size', '14px'),
  ('text-align', 'center'),
]

cell_hover_props = [
    ('background-color', '#eeeeef')
]

headers_props = [
    ('text-align','center'),
    ('font-size','1.1em')
]

styles = [
    dict(selector="th", props=th_props),
    dict(selector="td", props=td_props),
    dict(selector="td:hover",props=cell_hover_props),
    dict(selector='th.col_heading.level0',props=headers_props),
    dict(selector='th.col_heading.level1',props=td_props)
]

arrays = [
    ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
    ["one", "two", "one", "two", "one", "two", "one", "two"],
]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=[None, "Brand"])
df = pd.DataFrame(np.random.randn(3, 8), index=["A", "B", "C"], columns=index)

# 生成带样式的HTML
styled_html = df.style.set_table_styles(styles, overwrite=False).set_properties(**{'text-align':'center'}).to_html()

# 添加自定义CSS强制覆盖Streamlit默认样式
custom_css = """
<style>
    table.dataframe td {
        text-align: center !important;
    }
    table.dataframe th.col_heading {
        text-align: center !important;
    }
</style>
"""

# 用markdown渲染HTML和CSS
st.markdown(custom_css + styled_html, unsafe_allow_html=True)

关键说明:

  • !important规则:用来强制覆盖Streamlit内置的文本对齐样式,确保你的设置优先级更高。
  • 选择器针对性:table.dataframe td和table.dataframe th.col_heading是Streamlit渲染表格时用的类名,直接针对这些元素设置样式不会影响其他组件。
  • 保留原有样式:之前设置的字体、背景色、hover效果等都会完整保留,只是补充了强制对齐的规则。

这样修改后,单元格内容和多级表头都会正常居中,同时其他样式也能按预期生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:30:43