Setting the dbc.Card in the center of the page

Hi,

I have a dash bootstrap card and I want to align it in the center of the page.

Now I am lowering it with html.Div([], style={'margin-top':150}), but it is a hell of a job to do this for multiple pages with different card sizes. My code:

not_found = dbc.Card(
    [
        dbc.CardBody(
            [
                html.Div("404: The page you are looking for is not found."),
                html.Br(),
            ]
        )
    ],
    color="dark", outline=True, body=True, style={"width": "27rem"}
)

layout_not_found = html.Div([
    dbc.Row(
        [
            dbc.Col(not_found, width={'size': 3, 'offset': 0}),
        ], justify='around',
    )    
    ], style={'margin-top': 150})

What is the best way to get a card in the center of the layout?

Thanks in advance!
Vijay

I am assuming that you want to get it aligned horizontally and vertically (and vertically is the most important part!).

You can do something like this:

html.Div(
    dbc.Row(
        dbc.Col(
            dbc.Card("Test"),
            width=4,
        ),
        align="center",
        justify="center",
        style={"height": "100%"},
    ),
)

You must specify the parent height, otherwise you won’t be able to center vertically. Please refer to the great dbc documentation for more info on how to use the BS grid system.

1 Like

Thanks,

I tried with different justify and align parameters, but the card will remain at the top of the page.

I have found a workaround for not starting at the top of the page. That is by simply adding a navbar. This includes a standard spacing and, although not centred, the esthetic looks much better!

Vijay

I tried with different justify and align parameters, but the card will remain at the top of the page.

Have you defined the parent height to “100%”?

EDIT: Sorry, my bad… It should have been “100vh” instead of “100%”…

html.Div(
    dbc.Row(
        dbc.Col(
            dbc.Card("Test"),
            width=4,
        ),
        align="center",
        justify="center",
        style={"height": "100vh"}, # THIS!
    ),
)

Glad that you found a workaround… the code above should still work for your initial question.

1 Like