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

如何在Python Dash中居中显示图片?现有代码未生效求助

解决Dash中图片居中显示的问题

你当前代码里的align-self-center是Flex布局属性,但外层的html.Div默认并非Flex容器,所以这个样式无法生效,导致图片始终靠左。下面提供几种可行的解决方式:

方法一:使用dbc.Row和dbc.Col实现居中

利用Bootstrap的栅格布局,通过Col的Flex类让图片水平居中:

import dash
from dash import html, dcc
import dash_bootstrap_components as dbc

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Row(
    dbc.Col(
        dbc.CardImg(src=r'assets/welcome.png'),
        className="d-flex justify-content-center"
    )
)

if __name__ == '__main__':
    app.run_server(debug=True)

方法二:给外层Div添加Flex容器类

直接将外层Div设置为Flex容器,并用justify-content-center实现水平居中:

import dash
from dash import html, dcc
import dash_bootstrap_components as dbc

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = html.Div(
    dbc.CardImg(src=r'assets/welcome.png'),
    className="d-flex justify-content-center"
)

if __name__ == '__main__':
    app.run_server(debug=True)

方法三:用dbc.Card包裹CardImg

dbc.Card本身是Flex容器,此时align-self-center属性可以生效,同时让卡片占满宽度确保居中效果:

import dash
from dash import html, dcc
import dash_bootstrap_components as dbc

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = html.Div(
    dbc.Card(
        dbc.CardImg(src=r'assets/welcome.png', className="align-self-center"),
        className="w-100"
    ),
    className="w-100"
)

if __name__ == '__main__':
    app.run_server(debug=True)

注意:所有方案都需要确保在初始化Dash时引入Bootstrap样式(external_stylesheets=[dbc.themes.BOOTSTRAP]),否则dbc的CSS类无法生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:10:21