如何在 plotly dash 框架中居中对齐 table?

How to center-justify a table in plotly dash framework?

我是 dash 的新手,我正在尝试居中对齐我用函数创建的 table。我已经从 SQL 数据库中获取 table 的数据。在破折号布局中,我尝试为 table 本身使用样式,但它不起作用。样式仅适用于页面上的文本。 Df 是我没有发布的数据框,因为它与样式无关。我是否需要在布局中或在函数中创建 table 时应用样式?

def generate_table(dataframe, max_rows=1000):
    return html.Table([
        html.Thead(
            html.Tr([html.Th(col) for col in dataframe.columns])
        ),
        html.Tbody([
            html.Tr([
                html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
            ]) for i in range(min(len(dataframe), max_rows))
        ])
    ])


app.layout = html.Div(children=[
    html.H2(
        children='Products',
        style={
            'textAlign' : 'center' 
        }
    ),
    generate_table(df)
])

一个简单的解决方法是将 style={'marginLeft': 'auto', 'marginRight': 'auto'} 添加到 html.Table。所以你的函数会变成:

def generate_table(dataframe, max_rows=1000):
    return html.Table([
        html.Thead(
            html.Tr([html.Th(col) for col in dataframe.columns])
        ),
        html.Tbody([
            html.Tr([
                html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
            ]) for i in range(min(len(dataframe), max_rows))
        ])
    ], style={'marginLeft': 'auto', 'marginRight': 'auto'})

更好的办法是添加 className="center" 并将以下内容添加到 .css 文件中:

.center {
  margin-left: auto;
  margin-right: auto;
}