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

Plotly Dash如何基于视口尺寸切换不同布局?

Dash响应式布局实现:移动端垂直/桌面端左右切换

需求描述

移动端(视口尺寸xs)采用垂直布局:

+--------+  # mobile
  |  top   |
  |--------|
  |        |
  | middle |
  |        |
  |--------|
  | bottom |
  +--------+

桌面端(视口尺寸sm-xxl)采用左右布局:

+--------+ +--------+  # desktop
  |  top   | |        |
  |--------| | middle |
  | bottom | |        |
  +--------+ +--------+

单独布局实现

两种布局单独实现并不复杂:

# 移动端布局
dbc.Col([        
    dbc.Col(top),
    dbc.Col(middle),
    dbc.Col(bottom)
])

# 桌面端布局
dbc.Row([                   
    dbc.Col([top, bottom]),
    dbc.Col(middle)
])

问题:响应式切换未实现

尝试通过dbc.Col的order、offset和size参数实现响应式切换,但未达到预期效果。以下是调试代码及非预期效果:

调试代码

from dash import Dash, html
import dash_bootstrap_components as dbc

top = dbc.Col(
    html.H1('top'),
    style={'height': '10em', 'background-color': '#636EFA'}
)
middle = dbc.Col(
    html.H1('middle'),
    style={'height': '20em', 'background-color': '#EF553B'}
)
bottom = dbc.Col(
    html.H1('bottom'),
    style={'height': '8em', 'background-color': '#00CC96'}
)

layout = dbc.Row([
    dbc.Col(
        top,
        xs=dict(order=1, size=12),
        sm=dict(order=1, size=6)
    ),
    dbc.Col(
        middle,
        xs=dict(order=2, size=12),
        sm=dict(order=2, size=6)
    ),
    dbc.Col(
        bottom,
        xs=dict(order=3, size=12),
        sm=dict(order=3, size=6)
    )
])

app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dbc.Container(layout)
app.run_server(debug=True)

非预期效果

桌面端显示为三列并列(top、middle、bottom各占6份宽度),而非预期的左右两列布局;移动端虽为垂直排列,但结构不符合需求。

解决方案

核心思路是将top和bottom放在同一个父Col中,通过响应式参数控制该父Col与middle的排列顺序和宽度:

from dash import Dash, html
import dash_bootstrap_components as dbc

top = html.H1('top', style={'height': '10em', 'background-color': '#636EFA'})
middle = html.H1('middle', style={'height': '20em', 'background-color': '#EF553B'})
bottom = html.H1('bottom', style={'height': '8em', 'background-color': '#00CC96'})

# 组合top和bottom到同一列
left_column = dbc.Col([top, bottom], xs=12, sm=6)
right_column = dbc.Col(middle, xs=12, sm=6)

layout = dbc.Row([
    left_column,
    right_column
])

app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dbc.Container(layout)
app.run_server(debug=True)

原理说明

  • 移动端(xs):两个父Col的size均设为12,自动垂直排列,内部top和bottom自然上下分布,符合需求。
  • 桌面端(sm及以上):两个父Col的size设为6,各占一半宽度,形成左右布局,左侧包含top和bottom上下排列,右侧为middle,完美匹配预期效果。

如果需要更精细的顺序控制(比如特殊场景下调整显示顺序),可以结合order参数,示例如下:

left_column = dbc.Col([top, bottom], xs=dict(size=12, order=1), sm=dict(size=6, order=1))
right_column = dbc.Col(middle, xs=dict(size=12, order=2), sm=dict(size=6, order=2))

不过本需求中默认顺序已经满足,无需额外调整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:36:15