Scrollable dbc.Table with max height and sticky header

How can I set a max height for a dbc.Table (vertically scrollable) while maintaining a sticky header at the top. I can use an enclosing html.Div as discussed in this thread, but I don’t think that allows me to have a sticky header.

I have also tried adding style = {'position': 'sticky', 'top': '0'} to the html.Thead and individual html.Th elements, as well as applying some css like th { position: sticky; top: 0; }, but those haven’t seemed to work either. Thanks for any advice people can offer.

I did the same thing, but it works.

import dash_bootstrap_components as dbc
import pandas as pd
from dash import Dash, html, dcc

app = Dash(__name__)

df = pd.read_excel('stock2.xlsx')

table_header = [
    html.Thead(html.Tr([html.Th(i) for i in df.columns]),
               style={
                   'position': 'sticky',
                   'top': '0'
               })
]

table_body = [
    html.Tbody(
        [html.Tr([html.Td(str(c)) for c in r]) for r in df.to_records()])
]

app.layout = html.Div(dbc.Table(table_header + table_body, bordered=True),
                      style={
                          'max-height': '200px',
                          'overflow': 'auto'
                      })

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


Yo, here’s a quick reproducible example. The trick is to have your wrapping div have a position of relative and the header sticky.

app.py

from dash import Dash, html
import dash_bootstrap_components as dbc
import numpy as np
import pandas as pd


df = pd.DataFrame(np.random.rand(10, 3), columns=["a", "b", "c"])

app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div(
    dbc.Table.from_dataframe(df),
    className="table-wrapper"
)


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

 
assets/style.css

.table-wrapper {
  overflow: hidden auto;
  position: relative;
  max-height: 300px;
}

.table-wrapper > table > thead {
  position: sticky;
  top: 0;
  background: lightgray;
}

dash_table_sticky_header

2 Likes