Dash框架中Bootstrap容器右侧边距无法去除的问题
问题
用Python的Dash库制作仪表盘时,使用Bootstrap组件遇到右侧边距无法消除的问题。已经在dbc.Container上设置了class_name='m-0',也试过style={'margin': '0px'},但问题仍未解决。
代码如下:
# Layout app.layout = dbc.Container(children=[ dbc.Row([ dbc.Col([ html.Div(children=[ html.H5(children='BAJA UEA'), html.H6(children="Visualização dos dados da telemetria"), ]), ]), dbc.Col([ dcc.Dropdown(['2400', '4800', '9600', '115200'], id='baudrate-dropdown', value='9600', placeholder='Baudrate', style={'width': '150px'}), dcc.Dropdown(portList, id='ports-dropdown', value='portList[0]', placeholder='COM Ports', style={'width': '150px'}), dbc.Button('Connect', id='connect-button', style={'width': '150px'}), ], class_name='d-flex p-3 align-items-center justify-content-evenly'), ]), dbc.Row([ dbc.Col([ dcc.Graph( id='graph_temperature', figure=graph_temperature ), dcc.Graph( id='graph_velocidade', figure=graph_velocidade ), dcc.Graph( id='graph_PRM', figure=graph_PRM ), dcc.Graph( id='graph_ACC', figure=graph_ACC ) ]), dbc.Col([ ]) ]) ], class_name='m-0')
问题效果截图:
解决方案
1. 清除Container的默认内边距
Bootstrap的Container默认带有左右内边距,仅清除margin无效,需同时清除padding:
dbc.Container(..., class_name='m-0 p-0')
或用style强制覆盖:
dbc.Container(..., style={'margin': 0, 'padding': 0})
2. 清除全局body边距
Dash默认body可能带有边距,添加全局样式消除:
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.index_string = ''' <!DOCTYPE html> <html> <head> {%metas%} <title>{%title%}</title> {%favicon%} {%css%} <style> body { margin: 0; padding: 0; } </style> </head> <body> {%app_entry%} <footer> {%config%} {%scripts%} {%renderer%} </footer> </body> </html> '''
3. 调整Col组件的宽度分配
代码中空的dbc.Col会占用空间导致右侧留白,给Col指定宽度并移除空Col:
dbc.Row([ dbc.Col([...], width=6), dbc.Col([...], width=6) ]), dbc.Row([ dbc.Col([...], width=12) # 占满整行 ])
4. 使用流体容器
换成fluid容器让其占满整个视口宽度:
dbc.Container(..., class_name='m-0 p-0', fluid=True)
内容的提问来源于stack exchange,提问作者Gustavo de Araujo
相关产品推荐
相关产品推荐

