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

Dash-Bootstrap Components布局异常:列未横向排列而是垂直堆叠的问题排查

Dash-Bootstrap Components布局异常:列未横向排列而是垂直堆叠的问题排查

你遇到的问题其实是Dash-Bootstrap Components(DBC)最常见的入门坑之一——没有在初始化Dash应用时引入Bootstrap的CSS样式表。DBC的栅格布局(Row/Col组件)完全依赖Bootstrap的核心CSS来实现横向排列的栅格系统,缺少样式支持的话,Col组件就会退化成普通的块级元素,自然会垂直堆叠显示。

修复后的完整代码

import dash_bootstrap_components as dbc
from dash import Dash, html

# 关键:初始化app时指定Bootstrap样式表,这是解决布局问题的核心
app = Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

row = html.Div(
    [
        dbc.Row(
            [
                dbc.Col(html.Div("One of three columns 1")),
                dbc.Col(html.Div("One of three columns 2")),
                dbc.Col(html.Div("One of three columns 3")),
            ],
            align="start",
        ),
        dbc.Row(
            [
                dbc.Col(html.Div("One of three columns 4")),
                dbc.Col(html.Div("One of three columns 5")),
                dbc.Col(html.Div("One of three columns 6")),
            ],
            align="center",
        ),
        dbc.Row(
            [
                dbc.Col(html.Div("One of three columns 7")),
                dbc.Col(html.Div("One of three columns 8")),  # 修正了原代码里重复的"9"笔误
                dbc.Col(html.Div("One of three columns 9")),
            ],
            align="end",
        ),
        dbc.Row(
            [
                dbc.Col(html.Div("One of three columns 10"), align="start"),
                dbc.Col(html.Div("One of three columns 11"), align="center"),
                dbc.Col(html.Div("One of three columns 12"), align="end"),  # 修正了原代码里的"13"笔误
            ]
        ),
    ],
    className="pad-row",
)

app.layout = dbc.Container(fluid=True, children=[row])

app.run(debug=True, host="127.0.0.1", port=8051)

关键修改说明

  1. 添加Bootstrap样式依赖
    初始化Dash实例时传入external_stylesheets=[dbc.themes.BOOTSTRAP],这行代码会自动引入Bootstrap 5的核心CSS(你的DBC 2.0.0版本对应Bootstrap 5),让Row/Col组件拥有栅格布局的样式类,从而实现横向排列。

  2. 其他细节优化

    • 把from dash import *改为明确导入Dash, html,避免潜在的命名冲突,让代码更清晰
    • 修正了原代码里的几处内容笔误(重复的列名、错误的序号),不影响布局但让内容更合理

额外注意事项

  • 如果你想使用不同的Bootstrap主题,可以替换dbc.themes.BOOTSTRAP为内置主题,比如dbc.themes.SUPERHERO、dbc.themes.CYBORG等
  • 你的版本组合(Dash 3.0.1 + DBC 2.0.0)是完全兼容的,无需担心版本匹配问题
  • 运行修复后的代码后,不仅列会横向排列,Row的align属性、Col的align属性也能正常生效,实现内容的垂直对齐效果

备注:内容来源于stack exchange,提问作者Rolf Wester

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 20:18:02